[剑指offer] 18-2. 删除链表中重复的节点

文章目录

题目

在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留。

样例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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值