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
.
Problem Solving Ideas:
Create a new auxiliary header, using two pointers pre,p;
Start cycle judgment
1. Pre->next=p->next, stating that there is the same element, then p=p->next; know that P->next is empty or discovers new elements;
2. Judge P->next!=p, if there is the same element of the p will inevitably move backwards, then the judgment is established, Pre->next=p->next, the connection of new elements;
3.P does not move, then pre=pre->next, add this element
Code:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*deleteduplicates (ListNode *head) { if(Head==null)returnNULL; //if (head->next==null) return head;ListNode *newlist=NewListNode (0); NewList->next=Head; ListNode*pre=NewList; ListNode*p=Head; while(p!=NULL) { while(p->next!=null&&pre->next->val==p->next->val) P=p->Next; if(pre->next==p)//no move occurredPre=pre->Next; Else //occurs move to remove{Pre->next=p->Next; } P=p->Next; //pre=pre->next; } returnNewlist->Next; }};
[Leetcode]remove duplicates from Sorted List II