王廷瑋|數位醫療|智慧醫療: 203. Remove Linked List Elements WFU

2024年7月17日 星期三

203. Remove Linked List Elements

203. Remove Linked List Elements


給定一個鏈表的頭節點和一個整數 val,移除鏈表中所有節點值等於 val 的節點,並返回新的頭節點。

範例:

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


Python


# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
# Create a dummy node to simplify edge cases
dummy = ListNode(next=head)
current = dummy
while current.next:
if current.next.val == val:
# Remove the node by skipping it
current.next = current.next.next
else:
# Move to the next node
current = current.next
# Return the new head, which is the next node of dummy
return dummy.next

19.47MB, 43ms


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* removeElements(ListNode* head, int val) {
// Create a dummy node to simplify edge cases
ListNode* dummy = new ListNode(0, head);
ListNode* current = dummy;
while (current->next != nullptr) {
if (current->next->val == val) {
// Remove the node by skipping it
ListNode* temp = current->next;
current->next = current->next->next;
delete temp;
} else {
// Move to the next node
current = current->next;
}
}
// Get the new head, which is the next node of dummy
ListNode* newHead = dummy->next;
// Clean up the dummy node
delete dummy;
return newHead;
}
};

20.24MB, 7ms


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
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
// Create a dummy node to simplify edge cases
let dummy = new ListNode(0);
dummy.next = head;
let current = dummy;
while (current.next !== null) {
if (current.next.val === val) {
// Remove the node by skipping it
current.next = current.next.next;
} else {
// Move to the next node
current = current.next;
}
}
// Return the new head, which is the next node of dummy
return dummy.next;
};

53.79MB, 67ms