链表_删除链表中重复的结点
思路:因为重复的节点都要删除,因此需要标记重复开始前的上一个节点,又因为头结点有可能是重复的节点,为了操作方便,我们可以再链表前面设置一个空节点作为头结点,因此需要设置3个指针,第一个head指向头结点。第二个p用来标记重复节点的前面一个节点,第三个cur用来寻找重复的节点,一旦找到p就不移动了,cur继续往后寻找直到不是重复的节点。
参考答案
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
head = ListNode(-1)
p = head
p.next = pHead
cur = pHead
while cur and cur.next:
if cur.val != cur.next.val:
p = p.next
cur = cur.next
else:
val = cur.val
while cur and cur.val == val:
cur = cur.next
p.next = cur
return head.next
精简代码:
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
newhead = ListNode(-1)
phead = newhead
phead.next = head
while head and head.next:
if head.val != head.next.val:
phead = phead.next
head = head.next
else:
tmp = head.val
while head and head.val == tmp:
head = head.next
phead.next = head
return newhead.next