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

题意:

  给定一个单向链表中的任意结点,要求将此结点从链表中删除。

思路:

  比较巧妙,将当前结点伪装成下一个结点,然后将下一个结点删除即可。

C++:

 1 /**

 2  * Definition for singly-linked list.

 3  * struct ListNode {

 4  *     int val;

 5  *     ListNode *next;

 6  *     ListNode(int x) : val(x), next(NULL) {}

 7  * };

 8  */

 9 class Solution {

10 public:

11     void deleteNode(ListNode* node) {

12         

13         if(node == 0)

14             return ;

15         

16         node->val  = node->next->val;

17         

18         ListNode *del = node->next;

19         node->next = del->next;

20         

21         delete del;

22     }

23 };

 

你可能感兴趣的:(LeetCode)