我的代码:
class Solution:
def deleteDuplication(self, pHead: ListNode) -> ListNode:
head = ListNode(-1)
tail = head
while pHead:
if not pHead.next: # 最后一个结点
tail.next = pHead
tail = tail.next
pHead = pHead.next
elif pHead.val != pHead.next.val: # 非最后一个结点且相邻不等
tail.next = pHead
tail = tail.next
pHead = pHead.next
else: # 非最后一个结点且相邻相等
val = pHead.val # 所有值val的结点都该删除
while pHead and pHead.val == val:# 慢慢删除值相等的结点
pHead = pHead.next
tail.next = None
return head.next
- 完整代码:
MyList.py
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def show(self):
p = self
while p is not None:
print(p.val, end=' ')
p = p.next
print()
# 只返回头节点
def Create(data):
# print('data',data)
if len(data) < 1:
return None
head = ListNode(data[0])
tail = head
for i in range(1, len(data)):
tail.next = ListNode(data[i])
tail = tail.next
return head
JZ76.py
from myutils.MyList import *
class Solution:
def deleteDuplication(self, pHead: ListNode) -> ListNode:
head = ListNode(-1)
tail = head
while pHead:
if not pHead.next: # 最后一个结点
tail.next = pHead
tail = tail.next
pHead = pHead.next
elif pHead.val != pHead.next.val: # 非最后一个结点且相邻不等
tail.next = pHead
tail = tail.next
pHead = pHead.next
else: # 非最后一个结点且相邻相等
val = pHead.val # 所有值val的结点都该删除
while pHead and pHead.val == val:# 慢慢删除值相等的结点
pHead = pHead.next
tail.next = None
return head.next
if __name__ == '__main__':
pHead = Create([1, 2, 3, 3, 4, 4, 5])
pHead.show()
ans = Solution().deleteDuplication(pHead)
ans.show()