From 0c4a7fc4a2b7cacd70b238a660f233255c0540ff Mon Sep 17 00:00:00 2001 From: Gowry Sugathan <38757089+gowry189@users.noreply.github.com> Date: Thu, 8 Oct 2020 12:58:34 +0530 Subject: [PATCH] Solve reverse LInked List in java --- reverseLinkedList.java | 82 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 reverseLinkedList.java diff --git a/reverseLinkedList.java b/reverseLinkedList.java new file mode 100644 index 0000000..28a3c57 --- /dev/null +++ b/reverseLinkedList.java @@ -0,0 +1,82 @@ +/*https://www.hackerrank.com/challenges/reverse-a-linked-list/problem*/ + +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) { + SinglyLinkedListNode current = head; + SinglyLinkedListNode prev = null; + SinglyLinkedListNode next = null; + while(current!=null){ + next=current.next; + current.next=prev; + prev=current; + current=next; + } + head=prev; + return head; + } + + private static final Scanner scanner = new Scanner(System.in);