LeetCode OJ算法题(八十二):Remove Duplicates from Sorted List
2014-08-27 14:58
267 查看
题目:
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
Given
解法:
Remove Duplicates的链表版,设置一个指向已处理好的链表的尾部的指针tail,一个当前访问的节点的指针cur,还有一个指向前驱的指针pre。
当cur.val == pre.val时,cur,pre后移,如果不相等,tail.next指向cur,pre = cur,cur= cur.next,被删除的节点会由于没有引用指向它而被JVM GC掉
public static ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode cur = head.next;
ListNode pre = head;
while(cur != null){
if(cur.val == pre.val){
pre.next = cur.next;
cur.next = null;
cur = pre.next;
continue;
}
pre = cur;
cur = cur.next;
}
return head;
}
Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given
1->1->2, return
1->2.
Given
1->1->2->3->3, return
1->2->3.
解法:
Remove Duplicates的链表版,设置一个指向已处理好的链表的尾部的指针tail,一个当前访问的节点的指针cur,还有一个指向前驱的指针pre。
当cur.val == pre.val时,cur,pre后移,如果不相等,tail.next指向cur,pre = cur,cur= cur.next,被删除的节点会由于没有引用指向它而被JVM GC掉
public static ListNode deleteDuplicates(ListNode head) {
if(head == null) return null;
ListNode cur = head.next;
ListNode pre = head;
while(cur != null){
if(cur.val == pre.val){
pre.next = cur.next;
cur.next = null;
cur = pre.next;
continue;
}
pre = cur;
cur = cur.next;
}
return head;
}
相关文章推荐
- LeetCode OJ算法题(八十三):Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List II
- [Leetcode]Remove Duplicates from Sorted List II
- 82-Remove Duplicates from sorted list II
- LeetCode | Remove Duplicates from Sorted List II
- Remove Duplicates from Sorted List Total
- LeetCode: Remove Duplicates from Sorted List
- leetcode -- Remove Duplicates from Sorted List -- 很简单
- 第十二周:83. Remove Duplicates from Sorted List
- leetcode Remove DUplicates from Sorted List
- 83. Remove Duplicates from Sorted List
- [C++]LeetCode: 6 Remove Duplicates from Sorted List II
- LeetCode--Remove Duplicates from Sorted List II
- 83. Remove Duplicates from Sorted List
- leetcode[83]:Remove Duplicates from Sorted List
- (Leetcode 82) Remove Duplicates from Sorted List II (Java)
- [LeetCode] Remove Duplicate from Sorted Linkded List II
- Remove Duplicates from Sorted List 有序链表去重 D1F3
- 83. Remove Duplicates from Sorted List
- remove duplicates from sorted list, remove nth node