您的位置:首页 > Web前端 > Node.js

[237] Delete Node in a Linked List

2015-08-24 21:53 225 查看

1. 题目描述

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.

题目描述很简单,就是给定且只给定要删除的节点,完成删除操作,且给定的节点不为尾节点。

2. 解题思路

题目要求很简单,给定一个节点并删除,但是我们常用的删除方法是1->2->3,删除2时,将1->next = 2->next,并删除2,这样就完成了一个基本的删除,根据这样的思维模式,发现在只给定一个待删除节点的指针时,根本没办法实现,因为对于单项链表来说,给定后一个节点我们是无法查找到前一个节点的。

换一种方式思考,我们并不需要释放2所占有的空间,只需要将后一个节点的内容覆盖到2节点上,这样也就起到了删除2的效果,并且因为前一个节点是指向当前2所在地址的,所以也就免去了改变地址的操作,如下所示。

*2 = *2->next


但有一个问题是题目限定删除的节点不是尾节点,当2为尾节点是,2->next = NULL,*2 = NULL是否是一个不合法的操作呢?这点上有些不明白,还有些疑问。

3. Code

/**
* 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) {
*node = *(node->next);  // 将node指向的内容赋值为node->next指向的内容
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: