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

237. Delete Node in a Linked List

2015-12-20 02:30 597 查看
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.

Subscribe to see which companies asked this question

/**
* 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)
{
node->val=node->next->val;
node->next=node->next->next;
}
};


这题因为指明不会是尾结点,所以我就没对node的后继节点进行是否为空的判断了。这题的主题思想就是并不是直接删除node,而是将node的后继节点的值赋给node节点(值被保存,为后面删除做铺垫),这就说明node的值被覆盖了,这时再删除node的后继节点值,因为会重复,或者说不重要了可删除,就将node的后继指针跨过node->next,而是指向node->next->next,自然node->next就被从单链表上删掉了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: