1. 程式人生 > >LeetCode 237. Delete Node in a Linked List

LeetCode 237. Delete Node in a Linked List

hat 當前 bsp ive body gpo delet ould pan

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

題目不難,刪除節點,但是方法很巧,將後一個節點直接覆蓋當前節點,不需要頭指針也能刪除節點,唯一不足是不能刪除最後一個節點

代碼如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     void deleteNode(ListNode* node) {
12         ListNode *tmp = node->next;
13 node->val = tmp->val; 14 node->next = tmp->next; 15 delete tmp; 16 } 17 };

時間復雜度:O(1)

空間復雜度:O(1)

LeetCode 237. Delete Node in a Linked List