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
.
Subscribe to see which companies asked this question
Solution: Set two pointers Curr and next point to the adjacent two nodes, scan from the back, (1) If the two nodes that point to the value are equal, delete the node that next points to, and next move forward; (2) If the two node values are different, two nodes move forward.
/** 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 | | head->next = = NULL)returnHead; ListNode*curr = head, *next = head->Next; while(Next! =NULL) { if(Curr->val = = next->val) {ListNode* del =Next; Next= next->Next; Curr->next =Next; Deletedel; } Else{Curr=Next; Next= next->Next; } } returnHead; }};
Or with a pointer:
/** 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 | | head->next = = NULL)returnHead; ListNode* Curr =Head; while(Curr! = NULL && Curr->next! =NULL) { if(Curr->val = = curr->next->val) {ListNode* del = curr->Next; Curr->next = curr->next->Next; Deletedel; } ElseCurr= curr->Next; } returnHead; }};
It is important to note that a duplicate value may have occurred more than 2 times, so you cannot move the two pointers forward at the same time when a duplicate value is found.
[Leetcode]82. Remove duplicates from Sorted list sort linked list de-weight