class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class List:
def init_list(self, data):
# 判断是否为空
if len(data) == 0:
return None
else:
# 头结点
head = ListNode(data[0])
# 尾节点
tail = head
# 逐个为 data 内的数据创建结点, 建立链表
for i in data[1:]:
node = ListNode(i)
tail.next = node
tail = node
return head
def print(self, head):
while head:
print(head.val, end="->")
head = head.next
print(None)
a = [1, 2, 3, 3, 2, 1, 4, 1]
l = List()
res = l.init_list(a)
l.print(res)
class Solution:
def removeDuplicateNodes(self, head):
if not head:
return head
pre, cur = None, head
visited = set()
while cur:
if cur.val not in visited:
visited.add(cur.val)
pre = cur
cur = cur.next
else:
pre.next = cur.next
cur = cur.next
return head
head = res
ll = Solution().removeDuplicateNodes(head)
l.print(ll)
面试题 02.01. 移除重复节点
于 2024-04-09 15:53:27 首次发布