更新於 2024/06/18閱讀時間約 3 分鐘

[Leetcode] 83. Remove Duplicates from Sorted List

題目 : 83. Remove Duplicates from Sorted List

Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.


Example 1:

Input: head = [1,1,2]
Output: [1,2]

Example 2:

Input: head = [1,1,2,3,3]
Output: [1,2,3]


1.

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
# 將curr和temp指向head
# curr是目前要比對的數字
# temp是下一個要比對的數字
curr = temp = head

# 如果head是None直接回傳head
if head == None:
return head

# temp因為是下一個要比對的數字,所以讓他指向下一個node
temp = temp.next

# 進入while迴圈,直到沒有下一個可以比對的node
while temp != None:
# 如果目前的node值(curr)和下一個node值(temp)一樣
if curr.val == temp.val:
# temp指向下一個node,繼續比對
temp = temp.next
else: # 如果目前的node值(curr)和下一個node值(temp)不一樣
# 讓curr的下一個node指向temp
curr.next = temp
# 將temp和curr指向下一個node,繼續比對
temp = temp.next
curr = curr.next

# 最後要將curr的下一個node指向None
curr.next = None

return head






分享至
成為作者繼續創作的動力吧!
© 2024 vocus All rights reserved.