LeetCode Delete Node in a Linked List

OpenSoucre發表於2015-08-02

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 class Solution {
 2 public:
 3     void deleteNode(ListNode* node) {
 4         if( node->next == NULL){
 5             delete node;
 6             node = NULL;
 7         }
 8         swap(node->val, node->next->val);
 9         ListNode* nextNode = node->next;
10         node->next = nextNode->next;
11         delete nextNode;
12     }
13 };

 

相關文章