본문 바로가기

알고리즘/LeetCode

[JAVA] LeetCode 237 - Delete Node in a Linked List

 

Write a function to delete a node in a singly-linked list.

You will not be given access to the head of the list,

instead you will be given access to the node to be deleted directly.

It is guaranteed that the node to be deleted is not a tail node in the list.

 

단순 연결 리스트에서 노드를 삭제하는 함수를 작성하라.

너는 리스트의 head에 대한 접근 권한 대신에 삭제할 노드에 대한 접근 권한을 가진다.

삭제할 노드가 리스트 내 tail이 아니라는 것이 보장된다.

(영알못 주의)

 

 

풀이 방법

1. 삭제할 노드의 값을 다음 노드의 값으로 바꾼다.

2. 삭제할 노드의 next 노드를 다음 노드의 next 의 값으로 변경한다.

 

ex) 현재 연결 리스트에 [ 4, 5, 1, 9 ] 노드가 들어와있고, 삭제할 노드가 5라고 치자!

현재 매개변수로 넘어온 node의 값은 5이고 next는 1의 노드일 것이다.

이 때, node의 값을 1로 변경하고, 현재 노드의 next 값을 next 노드(1)의 next 노드(9)로 변경한다.

한 마디로, 5의 노드의 값을 1로 바꾸고 5의 next를 9로 변경하는 것... 이 무슨...

 

class Solution {
    public void deleteNode(ListNode node) {
        node.val = node.next.val;
        node.next = node.next.next;
    }
}

 

 

왜 비 추천이 8천개가 넘었는지 알 것 같은 어이없던 문제....