[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指向的内容 } };
相关文章推荐
- node.js 基础学习笔记1
- 【LeetCode】19. Remove Nth Node From End of List
- 不能将Lnode * 类型的值分配到Lnode * 类型的实体
- leetcode: (19) Remove Nth Node From End of List
- npm(node)的安装步骤
- node相关的碎碎念
- [LeedCode OJ]#237 Delete Node in a Linked List
- node-restify简介
- Nodejs学习路线图
- [LeetCode 222]Count Complete Tree Nodes
- Nodejs笔记—入门篇
- 简单搭建nodeJS服务,访问本地站点文件
- Leetcode: Count Complete Tree Nodes
- *Remove Nth Node From End of List
- NodeJs学习(一) 环境搭建
- 【8-23】node.js学习笔记
- Node.js中的this关键字
- leetcode #24 swap nodes in pairs 链表
- 24.Swap Nodes in Pairs
- struct file和struct inode