题目
基本思路
这是一个关于删除重复节点的链表问题,思路很明确,pre,cur两个指针就可以了,然后同时需要注意的是1. 先进行预判 ; 2.删除节点问题大多数都需要头节点方便操作;3. while循环的终止条件,到底谁空??
我一开始写了一个居然超时了,然后就简化了思路,减少判断的次数,将代码重新整合就OK了。
运行代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur = head
while cur:
while cur.next and cur.val == cur.next.val:
cur = cur.next
# 没有相同元素
if pre.next == cur:
pre = pre.next
else:
pre.next = cur.next
cur = cur.next
return dummy.next