【一天一道LeetCode】#237. Delete Node in a Linked List
2016-07-12 22:18
302 查看
一天一道LeetCode
(一)题目
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 -> 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* pre = node; ListNode* p = node->next; while(p!=NULL) { pre->val = p->val; if(p->next!=NULL) {//p没有到最后一个节点 pre = p; p = p->next; } else break;//p->next==NULL,代表遍历到最后一个节点了 } pre->next = NULL; delete p;//删除p } };
解题思路二
既然可以改变节点值,那么可以把给定node的后继节点值赋给node,然后删除node的后继节点/** * 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* temp = node->next; node->val = temp->val; node->next = temp->next; delete temp;//删除node的后继节点 } };
很奇怪,思路一的AC时间是12ms,思路二的AC时间是16ms。
想了很久都想不通,大家要是能够解释这个的,可以在下面留言!共同学习!
相关文章推荐
- 【一天一道LeetCode】#237. Delete Node in a Linked List
- node.js:url
- Node.js:url
- Node.js:服务器与数据流
- Node.js 常用 API
- NODEjs自动重启服务
- Leetcode 24. Swap Nodes in Pairs (Easy) (cpp)
- node.js windows下npm配置全局模块express.
- 对express中next函数的一些理解
- Build a RESTful API Using Node and Express 4
- Node.js-中文分词【1】-node-segment
- node.js安装
- Leetcode 237. Delete Node in a Linked List (Easy) (cpp)
- node -- all
- nodejs 常用 index
- 通过sed和awk获取集群最新挂掉的DataNode信息
- nodejs:express API之res.locals
- C#操作XML文档(XmlDocument、XmlNode、XmlAttribute、SelectSingleNode、SelectNodes、XmlNodeList)
- 116. Populating Next Right Pointers in Each Node && 117. Populating Next Right Pointers in Each Node II
- Leetcode 19. Remove Nth Node From End of List (Easy) (cpp)