[Leetcode] 83. Remove Duplicates from Sorted List

閱讀時間約 3 分鐘

題目 : 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:

raw-image
Input: head = [1,1,2]
Output: [1,2]

Example 2:

raw-image
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






7會員
36內容數
這裡會放一些我寫過的 Leetcode 解題和學習新技術的筆記
留言0
查看全部
發表第一個留言支持創作者!