Remove duplicates from Sorted List II
Given a sorted linked list, delete all nodes that has 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 .
Solution 1:
Use a del tag to delete the last duplicate character.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode deleteduplicates (ListNode head) { - if(Head = =NULL) { the return NULL; - } - - //record the head. +ListNode dummy =NewListNode (0); -Dummy.next =head; + AListNode cur =dummy; at - //To delete the last node in the list of duplications. - Booleandel =false; - - while(cur! =NULL) { - if(Cur.next! =NULL in&& Cur.next.next! =NULL -&& Cur.next.val = =cur.next.next.val) { toCur.next =Cur.next.next; +del =true; -}Else { the if(del) { *Cur.next =Cur.next.next; $del =false;Panax Notoginseng}Else { -Cur =Cur.next; the } + } A } the + returnDummy.next; - } $}View CodeSolution 2:
Use a pre, a cur to scan, and when you encounter duplicates, use the For loop to skip all duplicate elements with cur.
1 /**2 * Definition for singly-linked list.3 * public class ListNode {4 * int val;5 * ListNode Next;6 * ListNode (int x) {7 * val = x;8 * next = null;9 * }Ten * } One */ A Public classSolution { - PublicListNode deleteduplicates (ListNode head) { - if(Head = =NULL) { the return NULL; - } - -ListNode dummy =NewListNode (0); +Dummy.next =head; - +ListNode pre =dummy; AListNode cur =Pre.next; at - while(cur! =NULL&& Cur.next! =NULL) { - if(Cur.val = =cur.next.val) { - while(cur! =NULL&& Cur.val = =pre.next.val) { -Cur =Cur.next; - } in - //Delete all the duplication. toPre.next =cur; +}Else { -Cur =Cur.next; thePre =Pre.next; * } $ }Panax Notoginseng - returnDummy.next; the } +}View Code
Leetcode:remove duplicates from Sorted List II problem Solving report