题解 | #删除链表中重复的结点#
删除链表中重复的结点
http://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pHead ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplication(self , pHead: ListNode) -> ListNode:
# write code here
ppre = ListNode(-1)
pre = ListNode(-1)
ppre.next = pre
pre.next = pHead # 是为了保证输入只有1个元素时,可以不执行下面的while循环,直接进行return
while pHead and pHead.next: # pHead.next是为了保证输入只有1个元素时,可以不用执行本while循环,因为如果执行的话也是pre指向空
if pHead.next and pHead.val != pHead.next.val:
pre.next = pHead
pre = pre.next
pHead = pHead.next
else:
val = pHead.val
while pHead and pHead.val == val:
pHead = pHead.next
pre.next = pHead
return ppre.next.next