JZ56 删除链表中重复的结点
错误记录
- 1->1->2 头节点可能被删除
- 1->1->2->2
- 1->1->2->3->3->4->5->5
class Solution:
def find_no_repeat(self, node):
p = node
if p and p.next:
if p.val != p.next.val:
return p
p_no_re = p.next
while p_no_re and p.val == p_no_re.val:
p_no_re = p_no_re.next
return p_no_re
else:
return p
def deleteDuplication(self, pHead):
p = self.find_no_repeat(pHead)
while p and p != self.find_no_repeat(p):
p = self.find_no_repeat(p)
pHead = p
while p:
p_no_re = self.find_no_repeat(p.next)
while p_no_re and p.next != p_no_re:
p.next = p_no_re
p_no_re = self.find_no_repeat(p.next)
p.next = p_no_re
p = p_no_re
return pHead
book method 若当前节点是重复节点,则需将上一个节点的next与比当前节点值大的节点相连
class Solution:
def deleteDuplication(self, pHead):
newhead = ListNode('a')
newhead.next = pHead
pre, cur = None, newhead
while cur:
pre = cur
cur = cur.next
while cur and cur.next and cur.val == cur.next.val:
t = cur.val
while cur and t == cur.val:
cur = cur.next
pre.next = cur
return newhead.next
|