码迷,mamicode.com
首页 > 其他好文 > 详细

Delete Node in a Linked List

时间:2015-07-25 13:52:42      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:

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.

解题思路:
删除单链表中的节点,和之前的删除节点不同的是,它没有给出头节点,给出的是要删除的那个节点的指针,一般删除要知道删除节点的前一个节点,但是这道题我们不知道,所以我们可以用要删除节点的下一个节点的值将此节点的值覆盖掉,再删除下一个节点即可。

代码:

/**
 * 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=*node->next;
        if(node==NULL||node->next==NULL) return;
        ListNode* p=node;
        ListNode* s=p->next;
        p->val=s->val;
        p->next=s->next;
    }
};


版权声明:本文为博主原创文章,未经博主允许不得转载。

Delete Node in a Linked List

标签:

原文地址:http://blog.csdn.net/sinat_24520925/article/details/47055145

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!