王廷瑋|數位醫療|智慧醫療: 83. Remove Duplicates from Sorted List WFU

2024年7月5日 星期五

83. Remove Duplicates from Sorted List

83. Remove Duplicates from Sorted List


給定一個已排序的鏈表的頭節點,刪除所有重複的節點,使得每個元素只出現一次。返回排序後的鏈表。

範例 1:

輸入:head = [1,1,2] 輸出:[1,2]


Python


from typing import Optional

# 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]:
current = head

while current and current.next:
if current.val == current.next.val:
current.next = current.next.next
else:
current = current.next

return head

16.39MB, 41ms


C++


/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* current = head;
while (current != nullptr && current->next != nullptr) {
if (current->val == current->next->val) {
ListNode* temp = current->next;
current->next = current->next->next;
delete temp;
} else {
current = current->next;
}
}
return head;
}
};

15.37, 13ms


Javascript

/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
/**
* @param {ListNode} head
* @return {ListNode}
*/
var deleteDuplicates = function(head) {
let current = head;

while (current && current.next) {
if (current.val === current.next.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}

return head;
};

52.12MB, 66ms