[HackerRank] JAVA Linked List

OOSEDUS·2025년 3월 11일
0

해커랭크

목록 보기
5/13
post-thumbnail

문제

This exercise focuses on traversing a linked list. You are given a pointer to the node of a linked list. The task is to print the of each node, one per line. If the head pointer is , indicating the list is empty, nothing should be printed.

Function Description
Complete the printLinkedList function with the following parameter(s):

SinglyLinkedListNode Head: a reference to the head of the list

Print
For each node, print its data value on a new line (console.log in Javascript).

Input Format
The first line of input contains , the number of elements in the linked list.
The next lines contain one element each, the values for each node.

Note: Do not read any input from stdin/console. Complete the printLinkedList function in the editor below.

Constraints

, where is the element of the linked list.

Sample Input

STDIN   Function
-----   --------
2       n = 2
16      first data value = 16
13      second data value = 13

Sample Output

16
13

Explanation
There are two elements in the linked list. They are represented as 16 -> 13 -> NULL. So, the function should print 16 and 13 each on a new line.


첫번째 시도 : Success

    static void printLinkedList(SinglyLinkedListNode head) {
        if (head == null) return;
        else {
            System.out.println(head.data);
            printLinkedList(head.next);
        }
    }

알아야할 개념

1) Linked List 구현 방법

static class SinglyLinkedListNode {
        public int data;
        public SinglyLinkedListNode next;

        public SinglyLinkedListNode(int nodeData) {
            this.data = nodeData;
            this.next = null;
        }
    }

    static class SinglyLinkedList {
        public SinglyLinkedListNode head;
        public SinglyLinkedListNode tail;

        public SinglyLinkedList() {
            this.head = null;
            this.tail = null;
        }

        public void insertNode(int nodeData) {
            SinglyLinkedListNode node = new SinglyLinkedListNode(nodeData);

            if (this.head == null) {
                this.head = node;
            } else {
                this.tail.next = node;
            }

            this.tail = node;
        }
  • 각 node에는 자신의 data와 next node에 대한 정보가 들어있다.
  • List에는 head와 tail이 존재함
  • insert를 할때에는 만약 head가 null이면 현재 node를 head로 설정하고 tail을 자기 자신으로 설정함 -> 그 이후 insert하면 head가 null 이 아니기 때문에 현재 tail의 next node를 새로 들어온 node로 업데이트하여 연결하고 tail도 새로 들어온 node로 업데이트 하기
profile
성장 가능성 만땅 개발블로그

0개의 댓글