LeetCode-237
Links:https://leetcode.com/problems/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.
思路:
1 -> 2 -> 3 -> 4 -> NULL
1 -> 2 -> 4 -> 4 -> NULL
1 -> 2 -> 4 -> NULL
这样就删掉了第三个结点.(实际上是第四个…)
至于加上那个temp嘛…考虑了下内存问题…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
/** * 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 -> val = node->next->val; ListNode * temp = node->next; node -> next = node->next->next; delete temp; } } }; |
不知道对不对,反正AC了…
【LeetCode】237. Delete Node in a Linked List