2017年11月27日 星期一

[LeetCode] 237. Delete Node in a Linked List

轉自LeetCode

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.
<Solution>

這題難的點在於,題目就只給你要刪除 node 的指標

所以無法去改變前一個指標所指的位置

想法如下
  • 將下一個 node 的值,複寫到自己身上
  • 然後將自己的 next 指標,指到下下個 node
圖解如下
code 如下

C++
/**
* 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) {
node->val = node->next->val;
node->next = node->next->next;
}
};

C++ 還可以簡化成以下
/**
* 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) {
*node = *(node->next);
}
};

Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}

沒有留言:

張貼留言