Leetcode | | 82. Remove duplicates from Sorted List II

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.