https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Topic:
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
.
Ideas:
Requires two pointers, a is used to record the new linked list, B is used to traverse the old linked list, because only the delete operation requires a flag to mark the AB segment to be deleted. Also pay attention to the processing of the head node.
AC Code:
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Deleteduplicates (listnode*head) { A if(head==NULL) - returnNULL; -listnode* newhead=NewListNode (0);//To handle Head thenewhead->next=head; -listnode* a=newhead,*b=newhead->Next; - intNow=head->Val; - BOOLoccur_flag=false; + while(b->next!=NULL) { - if(b->next->val==Now ) { +occur_flag=true; A } at Else{ - if(occur_flag==true){ -a->next=b->next;//Delete duplicate numbers -B=a;//Update Pointers - } - Else{ inA=b; - } tooccur_flag=false; +Now=b->next->Val; - } theB=b->Next; * } $ if(occur_flag==true){Panax Notoginsenga->next=b->next;//Delete duplicate numbers -B=a;//Update Pointers the } + Else{ AA=b; the } + returnNewhead->Next; - } $};
Leetcode (82): Remove duplicates from Sorted List II