Remove duplicates from sorted list
Given a sorted Linked List, delete all duplicates such that each element appear only once.
For example,
Given1->1->2
, Return1->2
.
Given1->1->2->3->3
, Return1->2->3
.
Solution:
The general technique of a linked list is to add a pseudo-header node and then delete the pseudo-header node when it is returned, which can reduce the discussion in different situations.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* deleteDuplicates(ListNode* head) { ListNode* myHead=new ListNode(0); myHead->next = head; ListNode *p=myHead, *q; while(p->next!=NULL&&p->next->next!=NULL){ if(p->next->val == p->next->next->val){ q=p->next; p->next = p->next->next; delete q; }else{ p=p->next; } } p=myHead; myHead=myHead->next; delete p; return myHead; }};
[Leetcode] remove duplicates from sorted list