2.2.5 Remove Duplicates from Sorted List II
来源:互联网 发布:check windows version 编辑:程序博客网 时间:2024/06/05 20:18
Link: https://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
正确代码:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
我的思路:思路很简单。但是代码还是写的有问题。
Time: O(n), Space: O(1)
while嵌套一个while。 为什么?
我的初始代码:
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode pre = new ListNode(-1); pre.next = head; ListNode cur = head; while(cur.next != null){ if(cur.next.val != cur.val){ pre.next = cur; pre = cur; cur = cur.next; } else{ cur = cur.next; } } return head; }}
正确代码:
public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return head; ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; ListNode cur = head; while(cur != null){ //find the place to change pointer while(cur.next != null && cur.next.val == cur.val){ cur = cur.next; } if(pre.next == cur){ pre = pre.next; } else{ pre.next = cur.next; } cur = cur.next; } return dummy.next; }}
相关题目: 注意这一题和Remove Duplicates in Sorted List的区别。
两道题可以用while嵌套while来做,上一道还可以用while嵌套if/else来做
0 0
- 2.2.5 Remove Duplicates from Sorted List II
- 2.2.5 Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- LeetCode: Remove Duplicates from Sorted List II
- [Leetcode] Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove duplicates from sorted list II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- [LeetCode]Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List II
- linux内核文档翻译 位置:Documentation/arm/Setup
- hdu 2147 kiki's game, 入门基础博弈
- 分别用普通过程,面向对象过程,和继承方法实现拖拽效果
- struct linger 用法
- jsonObject的使用
- 2.2.5 Remove Duplicates from Sorted List II
- [转]Python Profile 工具性能分析
- 条款32:确定你的public继承塑模出is-a关系
- POJ-3171-Cleaning Shifts
- c++中判断指针类型对象
- spoj 220. Relevant Phrases of Annihilation
- 123
- yaffs2 源码错误 too few arguments to function 'yaffs_flush_file' 2014.08.22
- Let’s Make a Map/Bubble Map