题解 | #删除链表中重复的结点#
删除链表中重复的结点
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:
if not pHead:
return pHead
dummy = TreeNode(0)
dummy.next = pHead
pre = dummy
cur = pre.next
if cur:
back = cur.next
while back:
#如果不重复,向后平移三个指针
if cur.val != back.val:
pre = cur
cur = back
back = back.next
else:
#如果出现重复,找到重复节点后边的第一个节点
while back and cur.val == back.val:
back = back.next
#如果重复节点就是链表尾,直接删掉
if not back:
pre.next = None
return dummy.next
#删掉重复节点,更新cur和back
pre.next = back
cur = pre.next
back = cur.next
return dummy.next