237. Delete Node in a Linked List

  • Total Accepted: 133535
  • Total Submissions: 292943
  • Difficulty: Easy
  • Contributors: Admin

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.

Subscribe to see which companies asked this question.

分析


方法一

最笨的办法,把后面值挨个复制到千面
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    void deleteNode(ListNode* node) {
        //consider shift all the nodes' values in the right position of given node
         
        ListNode * pre = NULL;
        while(node->next){
            pre = node;
            node->val = node->next->val;
            node = node->next;
        }
        pre->next = NULL;
    }
};

方法二

1
2
3
4
5
6
7
8
class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode* next = node->next;
        *node = *node->next;
        delete next;
    }
};


 




posted @ 2017-02-20 16:05  copperface  阅读(144)  评论(0编辑  收藏  举报