今日已更新 305 条资讯 | 累计 19865 条内容
关于我们

Delete Node in a Linked List

Jaspreet singh 2026年06月10日 17:17 4 次阅读 来源:Dev.to

Problem Link - https://leetcode.com/problems/delete-node-in-a-linked-list/ This is one of those interview questions that looks impossible at first. Normally, to delete a node from a Linked List, we need access to the previous node. But in this problem, we're only given the node that needs to be deleted. No head. No previous pointer. So how do we remove it? Let's understand the trick. Problem Statement Write a function to delete a node in a singly linked list. You are not given the head of the list. Instead, you are given only the node that needs to be deleted. Example Input: 4 -> 5 -> 1 -> 9 node = 5 Output: 4 -> 1 -> 9 Initial Thought Normally we delete a node like this: prev.next = node.next But here: We don't have prev We don't have head So the usual deletion approach is impossible. Key Observation Although we cannot delete the current node directly, we can make it look like it never existed. Consider: 4 -> 5 -> 1 -> 9 We need to delete: 5 Instead of removing node 5 , copy the value of the next node into it. 4 -> 1 -> 1 -> 9 Now remove the next node. 4 -> 1 -> 9 The original value 5 has disappeared. Mission accomplished. Intuition Copy the next node's value into the current node. Skip the next node. The current node now behaves as if it was deleted. Since the problem guarantees that the given node is not the tail node, a next node will always exist. Dry Run Input 4 -> 5 -> 1 -> 9 node = 5 Current node: 5 Next node: 1 Step 1 Copy next node value. node.val = node.next.val List becomes: 4 -> 1 -> 1 -> 9 Step 2 Skip next node. node.next = node.next.next List becomes: 4 -> 1 -> 9 Done. Optimal Java Solution class Solution { public void deleteNode ( ListNode node ) { ListNode cur = node . next ; node . val = cur . val ; node . next = cur . next ; } } Even Shorter Version class Solution { public void deleteNode ( ListNode node ) { node . val = node . next . val ; node . next = node . next . next ; } } Complexity Analysis Metric Complexity Time Complexity O(1) Space Comp

本文内容来源于互联网,版权归原作者所有
查看原文