237.LeetCode Delete Node in a Linked List(easy)[单链表 删除节点]
2016-04-15 17:06
671 查看
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
the linked list should become
Subscribe to see which companies asked this question
因为只能取到删除节点的指针和它后面的指针,不能访问到前面的指针,所以只能将删除节点后面的内容往前覆盖删除节点。过程如下:
用两个指针,一个保存删除节点前的指针,一个保存删除节点的。
Supposed the linked list is
1 -> 2 -> 3 -> 4and you are given the third node with value
3,
the linked list should become
1 -> 2 -> 4after calling your function.
Subscribe to see which companies asked this question
因为只能取到删除节点的指针和它后面的指针,不能访问到前面的指针,所以只能将删除节点后面的内容往前覆盖删除节点。过程如下:
用两个指针,一个保存删除节点前的指针,一个保存删除节点的。
class Solution { public: void deleteNode(ListNode* node) { //因为只能取到删除节点的指针和它后面的指针,不能访问到前面的指针,所以只能将删除节点后面的内容往前覆盖删除节点 ListNode* p = node; ListNode* l = node; while(p->next != NULL) { p->val = p->next->val; l = p; p = p->next; } if(l != p) { l->next = NULL; delete p; }else delete p; } };
相关文章推荐
- 使用express(4.X)搭建第一个Web应用【Node.js初学】
- Installing node.js on ubuntu server 15.10
- 『奇葩问题集锦』npm install 报错 node-pre-gyp ERR! node-pre-gyp -v v0.6.25
- node authentication
- Unix Filesystem Organization
- 美团酒店Node全栈开发实践
- 理解Nodejs中的事件轮询机制
- webstorm中使用nodejs,npm 配置
- NodeJS、NPM安装配置步骤
- 错误:namenode无法自动切换成active
- Nodejs Express目录结构
- 19. Remove Nth Node From End of List
- NodeJS、NPM安装配置步骤(windows版本)
- nodejs利用nodemailer发送邮件
- node解析ini文件
- nodepad++不打开上次关闭的文件
- node.js npm 提示 Error: ENOENT stat 报错的解决方法
- 【leetcode】237. Delete Node in a Linked List
- hadoop namenode ha--手动切换
- LeetCode - Delete Node in a Linked List