[LeetCode] [C++] 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.
LeetCode 237在线测试
问题描述
给定一个单项链表,删除其中一个节点(排除尾节点)。只给定要删除节点的指针
思路分析
这道题要换一个思路,不能考虑将要删除节点node前面的节点的next直接指向node的下一个,因为node前面
那个节点的指针在单向链表中根本不可能获取到。再考虑到要删除的node不为尾节点,这里考虑采用node拷贝
替换的方式将当前要删除的node值完全拷贝为他后一个的值(将当前Node替换为后面一个实现删除的效果)
(node->val= node->next->val, node->next = nodex->next->next)
类似于深拷贝概念,将后面Node完整拷贝到前面,形成删除了前面节点的效果
代码验证
/**
* 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;
node->next = node->next->next;
}
}
};
总结注意
转换思维,不能寻找Node前一个节点的死路上遇到死胡同。 单项链表中,没法获取当前Node之前的Node
原创声明
作者:hgli_00
链接:http://www.cnblogs.com/lihuagang/p/leetcode_237.html
来源:博客园
著作权归作者所有,转载请联系作者获得授权。