[HackerRank] JAVA - Insert Linked List in Specific Position

OOSEDUS·2025년 3월 11일
0

해커랭크

목록 보기
8/13
post-thumbnail

문제

Given a pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position, and return the head node.

A position of 0 indicates the head, a position of 1 indicates one node away from the head, and so on. The head pointer given may be null, meaning that the initial list is empty.

Example
head refers to the first node in the list 1 → 2 → 3
data = 4
position = 2

Insert a node at position 2 with data = 4. The new list is 1 → 2 → 4 → 3

Function Description
Complete the function _insertNodeAtPosition _with the following parameters:

SinglyLinkedListNode pointer llist: a reference to the head of the list
data: an integer value to insert as data in the new node
position: an integer position to insert the new node, zero-based indexing

Returns
SinglyLinkedListNode pointer: a reference to the head of the revised list

Input Format
The first line contains an integer n, the number of elements in the linked list.
Each of the next n lines contains an integer SinglyLinkedListNode[i].data.
The next line contains an integer data, the data of the node that is to be inserted.
The last line contains an integer position.

Sample Input

STDIN   Function
-----   --------
3       n = 3
16      llist = 16->13->7
13
7
1       data = 1
2       position = 2

Sample Output

16 13 1 7

코드 : Success

class Result {

    public static SinglyLinkedListNode insertNodeAtPosition(SinglyLinkedListNode llist, int data, int position) {
        SinglyLinkedListNode beforeHead = llist;
        if (position == 0) {
            SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
            newNode.next = llist;
            return newNode;
        }
        for (int i = 0; i < position - 1; i++) {
            llist = llist.next;
        }
        SinglyLinkedListNode newNode = new SinglyLinkedListNode(data);
        SinglyLinkedListNode afterNode = llist.next;
        newNode.next = afterNode;
        llist.next = newNode;
        return beforeHead;
    }
}

로직

  • position이 0일때에는 가장 앞 head에 새로운 node를 넣어야하기에, 새로운 노드를 생성하고 next에 기존 head로 연결해준다.
  • 그 외의 경우에는 해당 position보다 한 자릿수 접근하여 새로운 노드를 해당 node의 next와 연결해준다. 새로운 노드는 원래 다음 자리의 노드를 next로 설정해준다.
profile
성장 가능성 만땅 개발블로그

0개의 댓글