解题思路与官方提供的一致,即遍历。但此处主要记录每次操作指针的走向
以【1,1,2,2,3】 为例
class Solution:
def deleteDuplicates(self,head):
if not head:
return head
# if head == None:
# return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
(1)未进入循环:
(2)第一次循环,且执行 if cur.val == cur.next.val 的判断
(3)第2次循环,且执行else的操作
(4)第3次循环,且执行 if cur.val == cur.next.val 的判断
(5)第4次循环,且执行else的操作
完整程序
"""
力扣题 :83.删除排序链表中的重复元素
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/
"""
class ListNode:
def __init__(self,val=0,next = None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self,head):
if not head:
return head
# if head == None:
# return head
cur = head
while cur.next:
if cur.val == cur.next.val:
cur.next = cur.next.next
else:
cur = cur.next
return head
arr = [1,1,2,2,3]
# arr=[]
pre = ListNode(0)
cur = pre
for j in range(len(arr)):
node = ListNode(arr[j])
cur.next = node
cur = cur.next
l2 = Solution().deleteDuplicates(pre.next)
while l2:
print(l2.val,end='')
l2 = l2.next