[LeetCode]82 删除排序链表中的重复元素II

题目描述

给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。

示例1:

输入: 1->2->3->3->4->4->5
输出: 1->2->5

示例2:

输入: 1->1->1->2->3
输出: 2->3

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
st, h, dup, fin = [], head, 0, 0
while h or (fin and dup):
if not fin and st and st[-1].val == h.val:
dup = 1
else:
if dup:
dup = 0
st.pop()
if st:
st[-1].next = h
else:
head = h
if fin:
return head
st.append(h)
while len(st) > 2:
del st[0]
h = h.next
fin = not h
return head