删除有序链表中的重复元素(python)
重复的留下一个
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
#空链表
if head == None:
return None
#遍历指针
cur = head
#指针当前和下一位不为空
while cur and cur.next:
#如果当前与下一位相等则忽略下一位
if(cur.val == cur.next.val):
cur.next = cur.next.next
#否则指针正常遍历
else:
cur = cur.next
return head
重复的不留
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
#空链表
if head == None:
return None
res = ListNode(0)
#在链表前加一个表头
res.next = head
cur = res
while cur.next and cur.next.next:
#遇到相邻两个节点值相同
if cur.next.val == cur.next.next.val:
temp = cur.next.val
#将所有相同的都跳过
while cur.next != None and cur.next.val == temp:
cur.next = cur.next.next
else:
cur = cur.next
#返回时去掉表头
return res.next

浙公网安备 33010602011771号