본문 바로가기

알고리즘/해커랭크

[해커랭크] Print in Reverse

문제링크: www.hackerrank.com/challenges/print-the-elements-of-a-linked-list-in-reverse/problem

 

Print in Reverse | HackerRank

Print the elements of a linked list in reverse order, from tail to head

www.hackerrank.com

직전 포스팅에 다른사람풀이의 대부분이 재귀로 해결했다고 얘기했다.

바로 이번 문제에서 바로 적용해봤다. 빠르게 떠올랐다.

import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    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;
        }
    }

    public static void printSinglyLinkedList(SinglyLinkedListNode node, String sep) {
        while (node != null) {
            System.out.print(node.data);

            node = node.next;

            if (node != null) {
                System.out.print(sep);
            }
        }
    }

    // Complete the reversePrint function below.

    /*
     * For your reference:
     *
     * SinglyLinkedListNode {
     *     int data;
     *     SinglyLinkedListNode next;
     * }
     *
     */
    static void reversePrint(SinglyLinkedListNode head) {
        if(head==null) return;
        reversePrint(head.next);
        System.out.println(head.data);

    }

    private static final Scanner scanner = new Scanner(System.in);