题目
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 -> 4
after calling your function.
解析
不知道前面的元素,没法删除节点,但是可以转换思维,把后面元素的值赋给前面的元素,再删除最后一个节点
我的代码:
class Solution {
public:
void deleteNode(ListNode* node) {
while (node->next->next)
{
ListNode *p = node->next;
node->val = p->val;
node = node->next;
}
node->val = node->next->val;
node->next = NULL;
}
};
不过耗时还挺多的。
网上看到代码更简短的
class Solution {
public:
void deleteNode(ListNode* node) {
if(node==NULL) return;
node->val = node->next->val;
node->next = node->next->next;
}
};
不过耗时比我还多,哈。
还有只用一行代码的,而且耗时还短。
class Solution {
public:
void deleteNode(ListNode* node) {
if(node==NULL) return;
*node=*node->next;
}
};
<span style="background-color: rgb(255, 255, 255);"><span style="font-family:KaiTi_GB2312;font-size:18px;">利用了给出的赋值语句。</span></span>