题目: 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.
给出一个单链表中某个节点的指针,删除这个节点并保证链接连续。
直接将next节点复制到当前节点上就可以了。
注意:1.最好把多余的节点空间释放掉 2. 复制是复制的节点,而不是复制指针
代码如下:
/**
* 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) {
ListNode* next = node -> next;
*node = *next;
delete next;
}
};