【leetcode】Remove Duplicates from Sorted List

时间:2023-12-25 22:30:32

题目简述

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

解题思路

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None class Solution:
# @param head, a ListNode
# @return a ListNode
def deleteDuplicates(self, head):
if head == None:
return head
pre = ListNode(-1)
p = ListNode(-1)
p = pre = head
while p != None:
if p.val == pre.val:
if p.next == None:
pre.next = None
else:
pre.next = p.next
p = pre.next
else:
p = p.next
pre = pre.next
return head