LeetCode 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:

image

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.

解法思路(一)

  • 这道题和一般的给定值 val,让在链表中找到相应的节点,然后删除不同,这道题直接给出了要删除的节点;
  • 一般在链表中删除节点,是要找到待删除节点的前驱节点,然后让前驱节点跨过待删除节点,指向待删除节点的后继节点;
  • 但在单链表中,直接给出一个节点,是无法访问到其前驱节点的,并且一般的链表相关问题都会指出,不允许改变节点中的值,只能改变节点的 next 的指向,看来这道题就是要直接操作节点中的值了;
  • 具体做法是,将待删除节点的后继节点的值赋给待删除节点,然后让待删除节点的 next 指向其后继的后继,从而将其后继节点从链表中删除,继而间接的删除了给出的节点;

解法实现(一)

时间复杂度
  • O(1);
空间复杂度
  • O(1);
关键字

无法访问节点的前驱节点 改变节点中的值 直接给出待删除的节点

实现细节
  • 题中说明了,链表最少两个节点,链表中节点都是不一样的,待删除的节点不是最后一个节点,给出的节点一定是在这样一个合法的链表中的,所以无需再考虑边界问题;
package leetcode._237;

public class Solution237_1 {

    public void deleteNode(ListNode node) {

        ListNode delNode = node.next;

        node.val = delNode.val;
        node.next = delNode.next;

    }

}

返回 LeetCode [Java] 目录

你可能感兴趣的:(LeetCode 237 Delete Node in a Linked List)