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

2024年7月5日 星期五

82. Remove Duplicates from Sorted List II

82. Remove Duplicates from Sorted List II


給定一個已排序的鏈表的頭節點,刪除所有具有重複數字的節點,只保留原鏈表中具有獨特數字的節點。返回排序後的鏈表。

範例 1:

輸入:head = [1,2,3,3,4,4,5] 輸出:[1,2,5]


Python


# Definition for singly-linked list.
from typing import Optional

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]:
# Create a dummy node to handle edge cases easily
dummy = ListNode(0, head)
prev = dummy
curr = head
while curr:
# If we encounter duplicates
if curr.next and curr.val == curr.next.val:
# Move until the end of duplicates sublist
while curr.next and curr.val == curr.next.val:
curr = curr.next
# Skip all duplicates
prev.next = curr.next
else:
# No duplicates, move prev pointer
prev = prev.next
# Move current pointer
curr = curr.next
return dummy.next

16.53MB, 36ms


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) {
// Create a dummy node to handle edge cases easily
ListNode* dummy = new ListNode(0, head);
ListNode* prev = dummy;
ListNode* curr = head;
while (curr) {
// If we encounter duplicates
if (curr->next && curr->val == curr->next->val) {
// Move until the end of duplicates sublist
while (curr->next && curr->val == curr->next->val) {
curr = curr->next;
}
// Skip all duplicates
prev->next = curr->next;
} else {
// No duplicates, move prev pointer
prev = prev->next;
}
// Move current pointer
curr = curr->next;
}
ListNode* newHead = dummy->next;
delete dummy; // free the allocated memory for dummy node
return newHead;
}
};

14.10MB, 3ms


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) {
// Create a dummy node to handle edge cases easily
let dummy = new ListNode(0, head);
let prev = dummy;
let curr = head;

while (curr) {
// If we encounter duplicates
if (curr.next && curr.val === curr.next.val) {
// Move until the end of duplicates sublist
while (curr.next && curr.val === curr.next.val) {
curr = curr.next;
}
// Skip all duplicates
prev.next = curr.next;
} else {
// No duplicates, move prev pointer
prev = prev.next;
}
// Move current pointer
curr = curr.next;
}

return dummy.next;
};

50.53MB, 55ms