Description
編寫代碼,移除未排序鏈表中的重複節點。保留最開始出現的節點。
示例1:
輸入:[1, 2, 3, 3, 2, 1]
輸出:[1, 2, 3]
示例2:
輸入:[1, 1, 1, 1, 2]
輸出:[1, 2]
提示:
鏈表長度在[0, 20000]範圍內。
鏈表元素在[0, 20000]範圍內。
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
Solution
class Solution:
def removeDuplicateNodes(self, head: ListNode) -> ListNode:
if not head:
return head
occurred = {head.val}
pos = head
# 枚舉前驅節點
while pos.next:
# 當前待刪除節點
cur = pos.next
if cur.val not in occurred:
occurred.add(cur.val)
pos = pos.next
else:
pos.next = pos.next.next
return head