Remove Duplicates from Sorted ListTotal accepted:89961 Total submissions:253975 difficulty:easy
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
.
Ideas:
Maintains two pointers pointing to the current node and adjacent to the next node. Comparing the current node to the next node value, the next node is deleted, and the two pointers are incremented by 1 steps at a time.
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) { - returnhead; - } thelistnode* p=head; -listnode* q=p->Next; -listnode*tem; - while(q!=NULL) { + if(q->val!=p->val) { -p=Q; +Q=q->Next; A}Else{ attem=Q; -Q=q->Next; -p->next=Q; - Deletetem; - } - } in returnhead; -}
leetcode:83 Remove duplicates from Sorted list-daily programming question 16th