Problem:
Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the Original list.
for example,
1->2->3->3->4->4->5 , Return 1->2->5 .
given 1->1->1->2->3 , Return 2->3 .
Hide TagsLinked ListTest instructions: Deleting duplicate elements of a single linked list
Thinking:
(1) Single-linked list sequential traversal, time complexity O (n), this problem is not difficult
(2) I use a double-pointer traversal, using the precursor pointer to save the most recent non-repeating nodes, easy to delete duplicate nodes, one time to submit AC
Code
/** * 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) {if (Head==null | | head->next==null) return head; if (Head->val==head->next->val)//starting from the beginning of the node repeating element {ListNode *tmp=head;; while (Tmp->next && tmp->val==tmp->next->val) {tmp=tmp->next; } return Deleteduplicates (Tmp->next); } ListNode *p=head;//left pointer listnode *q=p; Right pointer ListNode *pre=p; The precursor pointer while (p!=null) {q=p->next;//right pointer initializes the IF (Q==null) return head; if (p->val!=q->val)//unequal, while advancing {pre=p; The precursor pointer saves the last occurrence of the non-repeating node p=p->next; q=q->next; } elseEqual, right pointer forward {while (Q!=null && q->val==p->val) { q=q->next; } pre->next=q; Delete duplicate element p=q; Update left Pointer}} return head; }};
Leetcode | | 82. Remove duplicates from Sorted List II