Leetcode-Remove Duplicates from Sorted List II
2014-11-16 07:42
399 查看
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
Solution:
For example,
Given
1->2->3->3->4->4->5, return
1->2->5.
Given
1->1->1->2->3, return
2->3.
Solution:
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if (head==null || head.next==null) return head; ListNode preHead = new ListNode(-1); preHead.next = head; ListNode cur = head; ListNode pre = preHead; //NOTE:We need to be every carefull about the condition, //because if the last node be deleted, the cur is null in the next step. //however, if the node before the last node is deleted, the cur is the last node in the next step, //we then need to stop also, otherwise cur.next.val is invalid. while (cur!=null && cur.next!=null){ if (cur.val==cur.next.val){ while (cur.val==cur.next.val){ cur.next = cur.next.next; if (cur.next==null) break; } pre.next = cur.next; cur = pre.next; } else { pre = cur; cur = cur.next; if (cur.next==null) break; } } return preHead.next; } }
相关文章推荐
- [leetcode刷题系列]Remove Duplicates from Sorted List II
- leetcode 38: 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
- LeetCode:Remove Duplicates from Sorted List II
- LeetCode 82: Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List、Remove Duplicates from Sorted List II
- leetcode Remove Duplicates from Sorted List I && II
- LeetCode: Remove Duplicates from Sorted List II
- [leetcode] Remove Duplicates from Sorted List II
- [LeetCode] Remove Duplicates from Sorted List II, Solution
- [面试真题] LeetCode:Remove Duplicates from Sorted List I & 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