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++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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++ 還可以簡化成以下
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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; | |
} | |
} |
沒有留言:
張貼留言