Description
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
Solution
设置头节点和next节点,这个题与删除所有重复元素的剑指offer的一个题目类似。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
res = ListNode(-1e9)
res.next = head
pre, cur = res, head
while cur:
# 向后看
if cur.next and cur.next.val == cur.val:
cur = cur.next
else:
pre.next = cur
pre = cur
cur = cur.next
return res.next