237. Delete Node in a Linked List&在O(1)时间删除链表结点

来源:互联网 发布:c语言 多进程服务器 编辑:程序博客网 时间:2024/03/29 16:26

题目

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.

解答

  在这个问题中,无法访问链表的头结点,只能访问待删除的结点。方法很简单,直接将后继结点的数据复制到待删除的结点,然后删掉待删除结点的后继结点。
  这里写图片描述
  这里写图片描述
  

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) : val(x), next(NULL) {}};*/class Remove {public:    bool removeNode(ListNode* pNode) {        // write code here        if(!pNode || !pNode->next)        {            return false;        }        ListNode* next = pNode->next;        pNode->val = next->val;        pNode->next = next->next;        delete next;        return true;    }};

如果待删除的结点是链表的尾结点,那么该问题无解

0 0
原创粉丝点击