leetcode 删除单链表指定元素
2015-08-05 18:01
483 查看
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node p.
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.
一开始想到的是已经知道删除节点p之前的节点q,那么:
但是题目很明显只给出单链表要删除的节点p,其他信息不知,故不能直接采用上述写法,但是思想还是一致:可以把p下一位值赋给p,然后把p的下一位删除,因为我们已经知道p的下一位的前的节点:
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.
一开始想到的是已经知道删除节点p之前的节点q,那么:
q->next=p->next; delete p;
但是题目很明显只给出单链表要删除的节点p,其他信息不知,故不能直接采用上述写法,但是思想还是一致:可以把p下一位值赋给p,然后把p的下一位删除,因为我们已经知道p的下一位的前的节点:
void deleteNode(struct ListNode* node) { node->val=node->next->val; node->next=node->next->next; //delete p; }
相关文章推荐
- 在java程序中利用线程
- pom.xml和testng.xml
- BZOJ 1295 [SCOI2009]最长距离
- POJ1305(Fermat vs. Pythagoras 毕达哥拉斯三元组解不定方程)
- dom-drag.js
- Timer的利用
- 关于extjs下载excel文件使用到Ajax异步请求
- Leetcode41 First Missing Positive
- Android--应用安装卸载失败问题分析
- PowerDesigner之创建数据库物理模型
- SED的暂存空间和模式空间的一些操作
- oracle数据库注册表信息删除
- jQuery UI dialog 参数说明
- 【LeetCode】172 - Factorial Trailing Zeroes
- Shell - 打包,压缩及解压缩指令汇总
- 用C++实现单链表的创建、逆置和输出
- tomcat使用经验
- 人,贵有自知之明。
- 数据结构-----链表
- 两个二进制相加