Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2
, return 1->2
.
Given 1->1->2->3->3
, return 1->2->3
.
Hide TagsLinked ListIdea: A pair of pointers, a pointer to the node to be processed, a pointer to the processed node, compare the Val of two node equality, note that inequality is to be processed node->next = NULL, breaking the original link relationship.
/** 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; ListNode Dummy (-1); Dummy.next=Head; ListNode* p =Head; P= p->Next; while(p) {#if0cout<<"p->val\t"<< P->val <<Endl; cout<<"head->val\t"<< Head->val <<Endl; #endif if(P->val! = head->val) {Head->next =p; Head=p; } P= p->Next; //To break old link Head->next = NULL; } returnDummy.next; } };
Remove Duplicates from Sorted List