Delete Node in a Linked List

https://leetcode.com/problems/delete-node-in-a-linked-list/description/

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.

Thoughts

给的不是head而是要被删的结点而且没有往回找的pointer。没有走向parent的结点意味着真正意义上的删除不可能,只能通过把值往前移来simulate删除效果。

Code

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public void deleteNode(ListNode node) {
        while (node != null && node.next != null) {
            node.val = node.next.val;
            if (node.next.next == null) {
                node.next = null;
            }
            node = node.next;
        }
    }
}

Analysis

做题耗时5min.

时间复杂度O(n)

Last updated