标签:
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Given a sorted linked list, delete all nodes that have 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
.
题目:删除有序链表所有重复的结点
1 # Definition for singly-linked list. 2 # class ListNode: 3 # def __init__(self, x): 4 # self.val = x 5 # self.next = None 6 7 class Solution: 8 # @param {ListNode} head 9 # @return {ListNode} 10 def deleteDuplicates(self, head): 11 if head==None or head.next==None: 12 return head 13 dummy=ListNode(0) 14 dummy.next=head 15 p=dummy 16 tmp=dummy.next 17 while p.next: 18 while tmp.next and p.next.val==tmp.next.val: #1号结点值和2号结点值相等时 19 tmp=tmp.next #2号结点的指针后移继续判断3号结点,依次向后类推,直到while不满足即值不相等 20 #此时指针p和指针tmp前后标出了重复的结点段 21 if tmp==p.next: #情况1:若经上面判断没有重复项,即tmp指针没有移动,仍在初始p.next的位置处 22 p=p.next #将p后移一位 23 tmp=p.next #相应tmp仍在p后面即p.next位置,重新开始while p.next 及下面的循环判断 24 else: #情况2:tmp移动,标出了重复结点段,夹在p与tmp之间2个或多个重复结点 25 p.next=tmp.next #此时将tmp.next即重复段后面的链表部分直接连在p后,实现重复段的删除 26 return dummy.next
Remove Duplicates from Sorted List II
标签:
原文地址:http://www.cnblogs.com/lzsjy421/p/4607153.html