[HackerRank] JAVA - Delete Node

OOSEDUS·2025년 3월 11일
0

해커랭크

목록 보기
9/13
post-thumbnail

문제

Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value.

Example
llist = 0 → 1 → 2 → 3
position = 2

After removing the node at position 2, llist' = 0 → 1 → 3.

Function Description
Complete the deleteNode function in the editor below.
deleteNode has the following parameters:

  • SinglyLinkedListNode pointer llist: a reference to the head node in the list
  • int position: the position of the node to remove

Returns
SinglyLinkedListNode pointer: a reference to the head of the modified list
Input Format
The first line of input contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer, the node data values in order.
The last line contains an integer, position, the position of the node to delete.
Constraints
1 ≤ n ≤ 1000
1 ≤ list[i] ≤ 1000, where list[i] is the iᵗʰ element of the linked list.

Sample Input

8
20
6
2
19
7
4
15
9
3

Sample Output

20 6 2 7 4 15 9

코드

public static SinglyLinkedListNode deleteNode(SinglyLinkedListNode llist, int position) {
    // Write your code here
        SinglyLinkedListNode beforeHeadNode = llist;
        for(int i = 0; i < position - 1; i++) {
            llist = llist.next;
        }
        if(llist.next.next == null) {
                llist.next = null;
                return beforeHeadNode;
        }
        if(position == 0) {
            return llist.next;
        }
        SinglyLinkedListNode afterNode = llist.next.next;
        llist.next = afterNode;
        return beforeHeadNode;
    }

로직

  • 삭제해야할 position보다 1 작은 노드에 접근
  • 만약 삭제해야할 노드가 마지막 노드라면 현재 접근한 노드의 next 를 null로 설정
  • 만약 삭제해야할 노드가 head 노드라면 현재 노드의 next를 return하기
  • 이외의 경우에는 삭제해야하는 노드의 next노드를 현재 접근 노드의 next로 설정
profile
성장 가능성 만땅 개발블로그

0개의 댓글