leetCode 82.Remove Duplicates from Sorted List II (删除排序链表的重复II) 解题思路和方法
2015-07-22 13:29
375 查看
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
思路:这个题在刚开始做的时候想的有点,怎么都没办法正确解出。后面把代码全部删除重写,思路是记录当前节点p=head,然后head往下遍历,当head的值不等于head.next的值时,结束。比较p==head,相等说明没有重复,连接上;不相等说明有重复,跳过即可。
具体代码如下:
For example,
Given
1->2->3->3->4->4->5, return
1->2->5.
Given
1->1->1->2->3, return
2->3.
思路:这个题在刚开始做的时候想的有点,怎么都没办法正确解出。后面把代码全部删除重写,思路是记录当前节点p=head,然后head往下遍历,当head的值不等于head.next的值时,结束。比较p==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 first = new ListNode(0); ListNode last = first; ListNode p = head; while(head != null){ while(head.next != null){//p不动,head后移直到head.next与p不相等 if(p.val == head.next.val){ head = head.next;//相等循环 }else{ break;//不相等结束 } } if(p == head){//只有一个 last.next = p;//添加 last = last.next; } p = head = head.next;//有多个则不添加 last.next = null;//去掉关联 } return first.next; } }
相关文章推荐
- Weblogic启动报错
- zoj 1060 Sorting It All Out(拓扑排序)
- 《蛙》
- 创建单例
- 九度OJ 1192:回文字符串
- POJ 2823 Sliding Window(单调队列)
- git 和 vim 学习笔记
- no identifier specified for entity错误
- Frogger--poj2253
- Fragment-按返回键程序退出
- IIS减少工作线程阻塞的方法
- Linux内核中MD及RAID模块化
- python中的三元运算
- 【asp】asp网页utf-8乱码解决方法
- 引导页
- [POJ 3277]City Horizon
- leetCode 81.Search in Rotated Sorted Array II (旋转数组的搜索II) 解题思路和方法
- 提高工作效率的16条Android开发小经验
- SOAP和WSDL的一些必要知识
- Python中 字典排序、列表排序