本題Leetcode需進行鏈結串列刪除節點之實現,如下圖所示,該鏈結串列共有4個節點為4、5、1、9,在例子1中,若刪除節點為5,則需刪除節點5,因此鏈結串列為4、1、9,若刪除節點為1,則鏈結串列為4、5、9。

Example 1:
Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.
Example 2:
Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.
作法解析:本例子之鏈結串列指標指在5的位置,而該例子需刪除節點5,因此,將節點1之值複製給節點5,並透過連結節點5以及9的位置,即可得到輸出為4、1、9之鏈結串列。
程式碼:
**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
ListNode *p = node;
p->val = p->next->val;
p->next = p->next->next;
}
};
程式解析:
1.p->val = p->next->val; 將下一個節點之值複製給該節點。
2.p->next = p->next->next; 將下下節點與該節點串接,即達成刪除下個節點之功能。
請先 登入 以發表留言。