LeetCode Delete Node in a Linked List

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list — head = [4,5,1,9], which looks like following:

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.

Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function.

Note:

  • The linked list will have at least two elements.
  • All of the nodes’ values will be unique.
  • The given node will not be the tail and it will always be a valid node of the linked list.
  • Do not return anything from your function.237. Delete Node in a Linked List

删掉单向链表中的某个指定的节点,这个节点不是尾节点。 本科面试的时候遇到过这个题,当时好像没做出来…因为要删掉某个节点,肯定要知道其前驱节点prior,然后prior->next=prior->next->next。但是这一题只让访问当前节点,单向链表又无法获取其前驱节点,所以当时想了很久都没解出来。 今天灵光一闪,只能访问当前节点,又得不到其前驱节点,唯一可以知道的是其后继节点,所以我们可以不用真正的删掉当前节点,可以把后继节点的值赋给当前节点,然后删掉后继节点! 想到这一点就很简单了,也许这也是为什么题目说不包括尾节点,因为删掉尾节点不能用上述方法,只能用其前驱节点删除。 完整代码如下:

class Solution {
public:
    void deleteNode(ListNode* node)
    {
        node->val = node->next->val;
        ListNode *no_use=node->next;
        node->next = node->next->next;
        delete no_use;
    }
};

本代码提交AC,用时13MS。

Leave a Reply

Your email address will not be published. Required fields are marked *