题解 | #删除有序链表中重复的元素-II#
删除有序链表中重复的元素-II
https://www.nowcoder.com/practice/71cef9f8b5564579bf7ed93fbe0b2024
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @return ListNode类
#
class Solution:
def deleteDuplicates(self , head: ListNode) -> ListNode:
# write code here
dummy_head = ListNode(-1000000000000)
dummy_head.next = head
if head is None:
return None
pre, cur, nxt = dummy_head, head, head.next
while cur:
if nxt and cur.val == nxt.val:
while nxt and cur.val == nxt.val:
nxt = nxt.next
pre.next = nxt
else:
pre = cur
cur = nxt
if nxt:
nxt = nxt.next
return dummy_head.next
使用三个指针pre,cur,nxt分别记录,nxt 指针会一直向前移动,直到找到与cur指针值不等的节点或者链表的末尾。然后更新pre指针的next为nxt,从而删除所有重复的节点。同时,每次循环结束时,cur指针都会更新为nxt指针,以进行下一轮的判断。这样,代码应该能够正确地处理重复的元素,并返回一个只包含不重复元素的新链表。
360集团公司氛围 352人发布