您的位置:首页 > Web前端 > Node.js

【一天一道LeetCode】#237. Delete Node in a Linked List

2016-07-12 22:18 302 查看

一天一道LeetCode


本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处



(一)题目


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。

想了很久都想不通,大家要是能够解释这个的,可以在下面留言!共同学习!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: