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.
分析:
给你要删除的节点指针,将他删除,第一次意思读错了,草。
卧槽,对于1 -> 2 -> 3 -> 4,如何得知2的next指针呢?不知道能重新建立连接?
稍微看了一下,别人家的分析猛然醒悟:
将要删除的3改为下一个节点的值(所以要删除的节点不能是末尾),然后将要删除的3和4的下一个节点建立连接
/**
* 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)//不能是末尾
return;
ListNode* delnode=node->next;
node->val=node->next->val;//3->4
node->next=node->next->next;//3---null
delete delnode;
}
};
注:本博文为EbowTang原创,后续可能继续更新本文。如果转载,请务必复制本条信息!
原文地址:http://blog.csdn.net/ebowtang/article/details/50489486
原作者博客:http://blog.csdn.net/ebowtang
参考资源:
【1】网友,孙大胃,博文地址,http://blog.csdn.net/sunao2002002/article/details/47083975