题目
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。
样例1
输入:1->2->3->3->4->4->5
输出:1->2->5
样例2
输入:1->1->1->2->3
输出:2->3
思路
有序链表,因此重复的节点一定是相邻的。可以用快慢指针确定重复区域然后删除。
特殊测试用例:
【1】头节点重复,被删除
【2】尾节点重复
【3】链表中所有节点均重复
【4】有多段重复
代码
第一次代码,没考虑到多段重复的情况,删除完第一段重复节点程序就无法继续运行了。
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy=ListNode(0) #虚拟头节点,方便操作head
dummy.next=head
while head.next and head.val!=head.next.val:
pre=head
head=head.next
f=head.next
while f.val==f.next.val: # 长指针寻找区间右边界
f=f.next
pre.next=f.next #程序无法继续遍历剩余节点
return dummy.next
第二次代码,在最外层加了一个大循环,使用cur遍历整个链表。
而cur.val与cur.next.val相等或不等的两种情况,由if判断并分支处理。
对于cur.val==cur.next.val的情况,仍需要while循环来找到重复数值区间。这里借鉴了别人方法,不再额外使用变量f来找区间右边界,而是直接使用cur变量后移。最后cur停在区间最右端,同样要被删除。将cur.next赋给pre.next使得链表不断裂之后,需要同时把cur.next赋给cur,也就是继续遍历剩余的链表节点。
仍然无法AC!找了很久原因!
因为while循环条件只写了cur.next而没写cur!
不可以while cur.next:
一定要同时while cur and cur.next:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteDuplication(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy=ListNode(0)
dummy.next=head
pre,cur=dummy,head
while cur and cur.next: # 这里需要加上cur! 不加就错!
if cur.val==cur.next.val:
while cur and cur.next and cur.val==cur.next.val:
cur=cur.next
pre.next=cur.next # 此时cur也因重复而被删掉,将cur.next节点连在pre节点后
#cur=cur.next # 无论cur是不是重复,都要更新cur.next作为新cur,因此一并写在最后了
else:
pre=cur # 或者pre=pre.next,一样的
#cur=cur.next
cur=cur.next
return dummy.next