leetCode 237. Delete Node in a Linked List 鏈表

237. Delete Node in a Linked List

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 -> 4after calling your function.

題目大意:

給定單鏈表中的一個節點,刪除這個節點。

思路:

由於不能知道這個節點的前一節點,所以可以採用將當前要刪除的節點的信息與這一節點的下一節點的信息交換。然後刪除下一個節點。這樣就實現了刪除這個節點。

代碼如下:

/**
 * 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) {
        if(NULL == node)
            return ;
        ListNode * next = node->next;
        node->val = next->val;
        node->next = next->next;
        delete next;
    }
};

題目不是很好懂。

2016-08-12 21:05:17

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章