2 minute read

Problem

There is a singly-linked list head and we want to delete a node node in it.

You are given the node to be deleted node. You will not be given access to the first node of head.

All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list.

Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean:

  • The value of the given node should not exist in the linked list.
  • The number of nodes in the linked list should decrease by one.
  • All the values before node should be in the same order.
  • All the values after node should be in the same order.

Custom testing:

  • For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list.
  • We will build the linked list and pass the node to your function.
  • The output will be the entire list after calling your function.

Example 1:

image

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:

image

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.

Constraints:

  • The number of the nodes in the given list is in the range [2, 1000].
  • -1000 <= Node.val <= 1000
  • The value of each node in the list is unique.
  • The node to be deleted is in the list and is not a tail node.

Solution

/**
 * 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.next.next != null) {
            node.val = node.next.val;
            node = node.next;
        }
        node.val = node.next.val;
        node.next = null;
    }
}
// 뒤 값들을 땡기고.마지막 값을 없애면?

Explanation

  • 삭제되어야 할 노드가 파라미터로 주어지기 때문에 해당 노드의 앞의 노드로 이동할 수 없다. 고로 삭제되어야 할 노드의 뒤에 있는 노드를 활용해서 노드를 삭제해야 한다.
  • 삭제되어야 할 노드의 뒷 노드들의 값을 하나씩 앞으로 당겨와 값을 덮어씌우면 문제를 해결할 수 있다.
    while (node.next.next != null) {
      node.val = node.next.val;
      node = node.next;
    }
    
  • 마지막 노드가 Linked List에서 사라질 수 있도록 null을 할당해준다.
    node.val = node.next.val;
    node.next = null;
    

Categories:

Updated:

Leave a comment