leetcode - Delete Node in a Linked List

leetcode - 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 -> 4 after 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(node != NULL && node->next != NULL){
            ListNode* tp = node->next;
            node->val = tp->val;
            node->next = tp->next;
            delete tp;
        }
    }
};

  重点在于只提供了要删除的节点的指针。但是这个指针并不是前一个节点的next指针。所以一定要把后一个节点覆盖到这个节点,然后删除后一个节点才行。

posted @ 2015-07-22 09:57  cnblogshnj  阅读(145)  评论(0)    收藏  举报