"One Day together Leetcode" #82. Remove duplicates from Sorted List II

Source: Internet
Author: User

One Day together Leetcode

This series of articles has all been uploaded to my github address: Zeecoder ' s GitHub
You are welcome to follow my Sina Weibo, my Sina Weibo blog
Welcome reprint, Reprint please indicate the source

(i) Title

Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the original List.

For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

(ii) Problem solving

Delete the duplicate nodes in the linked list.

But all linked list problems, do not pay attention to the chain list, broken links and other conditions

Specific ideas to see the code:

/** * 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)returnHead//list is emptylistnode* newhead = NULL;//New list headerlistnode* newtail = NULL;//New-link listlistnode* p = head;BOOLIshead =true;//Identify the head of the new linked list          while(P!=null) {listnode* Pnext = p->next;intCount =1; while(Pnext!=null&&pnext->val==p->val) {///whether subsequent nodes and P are duplicatedcount++;             Pnext = pnext->next; }if(count==1){//equals 1 means no duplicates                 if(Ishead) {Newhead = P;newtail = Newhead;newtail->next=null;ishead =false;}//Head node requires special handling.                 Else{newtail->next = p;                     Newtail = newtail->next; newtail->next=null;//Note here Be sure to point the tail node next to null, or point to the original list of P's next.}} p = Pnext; }returnNewhead; }};

"One Day together 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.