문제링크: www.hackerrank.com/challenges/reverse-a-linked-list/problem
현재 노드의 다음 노드가 나를 가리키게 하는것을 재귀를 통해 해결한다.
처음에 현재 노드의 다음노드를 나를 가리키게 하는 것까지 하고 무한루프가 돌았다.
현재노드의 next를 null로 바꾸어주어서 문제가 해결됐다.
temp는 tail을 계속 리턴한다.
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, BufferedWriter bufferedWriter) throws IOException {
while (node != null) {
bufferedWriter.write(String.valueOf(node.data));
node = node.next;
if (node != null) {
bufferedWriter.write(sep);
}
}
}
// Complete the reverse function below.
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
static SinglyLinkedListNode reverse(SinglyLinkedListNode head) {
if( head.next==null)
return head;
SinglyLinkedListNode temp = reverse(head.next);
head.next.next = head;
head.next = null;
return temp;
}
private static final Scanner scanner = new Scanner(System.in);
'알고리즘 > 해커랭크' 카테고리의 다른 글
[해커랭크] Get Node Value (0) | 2021.01.14 |
---|---|
[해커랭크] Compare two linked lists (0) | 2021.01.13 |
[해커랭크] Print in Reverse (0) | 2021.01.13 |
[해커랭크] Delete a Node (0) | 2021.01.13 |
[해커랭크] Insert a node at a specific position in a linked list (0) | 2021.01.13 |