删除重复节点
2016-01-05 22:41
597 查看
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
Subscribe to see which companies asked this question
思路:后面的与当前的相同删除后面的即可,但是这种方法只能删除连续重复的(即1,1,1这种1,2,1这种无法删除)
代码:
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->2->3.
Subscribe to see which companies asked this question
思路:后面的与当前的相同删除后面的即可,但是这种方法只能删除连续重复的(即1,1,1这种1,2,1这种无法删除)
代码:
import java.util.ArrayList; /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode node = head; for(;node!=null;node=node.next){ while(node.next!=null&&node.val==node.next.val){ if(node.next==null)node=null; node.next = node.next.next; } } return head; } }递归的(有木有很赞啊!!虽然不是我写的(* ——*))
public ListNode deleteDuplicates(ListNode head) { if(head == null || head.next == null)return head; head.next = deleteDuplicates(head.next); return head.val == head.next.val ? head.next : head; }
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode pre = new ListNode(-1);//to avoid the head check pre.next = head; ListNode cur = pre; //ListNode node = head; while(cur.next!=null){ if(cur.next.val==cur.val)cur.next = cur.next.next; else cur = cur.next; } return head; } }
相关文章推荐
- java对世界各个时区(TimeZone)的通用转换处理方法(转载)
- java-注解annotation
- java-模拟tomcat服务器
- java-用HttpURLConnection发送Http请求.
- java-WEB中的监听器Lisener
- Android IPC进程间通讯机制
- Android Native 绘图方法
- Android java 与 javascript互访(相互调用)的方法例子
- 介绍一款信息管理系统的开源框架---jeecg
- 聚类算法之kmeans算法java版本
- java实现 PageRank算法
- PropertyChangeListener简单理解
- [C/C++]反转链表
- c++11 + SDL2 + ffmpeg +OpenAL + java = Android播放器
- 插入排序
- 冒泡排序
- 堆排序
- 快速排序