[leetcode] 237. Delete Node in a Linked List 解题报告
2015-12-27 15:14
751 查看
题目链接:https://leetcode.com/problems/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
with value
思路:很有意思的一题,要删除一个结点,但是只给了这一个结点。按说我们要删除要给结点要知道他的前一个结点,但是这题我们可以让他的值和后续结点交换,然后删除后续结点。
代码如下:
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 -> 4and you are given the third node
with value
3, the linked list should become
1 -> 2 -> 4after calling your function.
思路:很有意思的一题,要删除一个结点,但是只给了这一个结点。按说我们要删除要给结点要知道他的前一个结点,但是这题我们可以让他的值和后续结点交换,然后删除后续结点。
代码如下:
/** * 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) { ListNode* tem = node->next; swap(node->val, tem->val); node->next = tem->next; delete tem; } };
相关文章推荐
- 【实践】nodeJS写个简单的爬虫程序
- leetcode - Populating Next Right Pointers in Each Node II
- nodejs+chromium 创建桌面应用程序
- hadoop namenode ha--手动切换
- nodejs npm常用命令
- 用node开发repl应用
- Yum安装nodejs + npm之CetnOS 6.5
- nodejs认证模块passport.js参数解释
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- Node.js and Forever “exited with code: 0”
- 填坑系列: nodejs后台在支付宝异步通知时获取到的参数为空(使用koa模块)
- leetcode:19 Remove Nth Node From End of List-每日编程第三十六题
- Ubuntu14.04 快速配置 nodejs
- [Node.js] node-persist: localStorage on the server
- rabbitmq php pub nodejs sub
- 读书笔记之-node入门
- Web平台能从Node.js学到什么
- leetCode24:Swap Nodes in Pairs