Remove duplicates from Sorted List II

Source: Internet
Author: User

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/

Remove duplicates from Sorted List II

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 .

Title: Deleting all duplicate nodes of an ordered list

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param {ListNode} head9     #@return {ListNode}Ten     defdeleteduplicates (Self, head): One         ifHead==noneorhead.next==None: A             returnHead -dummy=listnode (0) -dummy.next=Head thep=Dummy -tmp=Dummy.next -          whileP.next: -              whileTmp.next andP.next.val==tmp.next.val:#when the junction value of number 1th is equal to the value of number 2nd nodes. +Tmp=tmp.next#the pointer behind the number 2nd node continues to determine the number 3rd node, and then backwards and forwards until the while is not satisfied values are not equal . -                                                           #A duplicate node segment is marked before and after the pointer p and the TMP +             ifTmp==p.next:#Scenario 1: If no duplicates are judged by the above, the TMP pointer is not moved and is still in the initial p.next position AP=p.next#move p back one atTmp=p.next#The corresponding TMP is still in the P.next position after p, restarting the while P.next and the following loop judgment -             Else:#The situation 2:tmp moved, marked the repeating node segment, sandwiched between P and TMP 2 or more repeating nodes . -P.next=tmp.next#at this point, tmp.next that is the repeating segment after the linked list part directly connected to P, to achieve the deletion of the repeating segment -         returnDummy.next

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.