From 756589e27280187a0079fe03eebb28451e83307f Mon Sep 17 00:00:00 2001 From: Toihir Halim <66559721+toihirhalim@users.noreply.github.com> Date: Wed, 14 Apr 2021 05:43:37 +0200 Subject: [PATCH] Add reverse linked list in java (#182) --- linked-lists/README.md | 1 + linked-lists/java/reverse.java | 78 ++++++++++++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 linked-lists/java/reverse.java diff --git a/linked-lists/README.md b/linked-lists/README.md index 0eb09c14..828349b0 100644 --- a/linked-lists/README.md +++ b/linked-lists/README.md @@ -14,6 +14,7 @@ 1. [Singly Linked List](java/singly.java) 2. [Doubly Linked List](java/doubly.java) 2. [Circular Linked List](java/circular.java) +2. [Reverse Linked List](java/reverse.java) ### JavaScript diff --git a/linked-lists/java/reverse.java b/linked-lists/java/reverse.java new file mode 100644 index 00000000..28d04ede --- /dev/null +++ b/linked-lists/java/reverse.java @@ -0,0 +1,78 @@ +class LinkedList{ + class Node{ + int item; + Node next; + + public Node(int item) { + this.item = item; + } + } + + Node head = null; + + public void addNode(int item){ + Node newElem = new Node(item); + + if(this.head != null){ + newElem.next = this.head; + } + + this.head = newElem; + } + + public void reverse(){ + Node prev = null; + Node current = this.head; + Node next = null; + + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + this.head =prev; + } + + public void print() { + Node current = head; + if(head == null) return; + System.out.print("[ "); + while(current != null) { + System.out.print(current.item + " "); + current = current.next; + } + System.out.println("]"); + } +} + +public class reverse{ + + public static void main(String [] args){ + LinkedList list = new LinkedList(); + + list.addNode(2); + list.addNode(7); + list.addNode(1); + list.addNode(8); + list.addNode(5); + + System.out.print("before : \t"); + list.print(); + + list.reverse(); + + System.out.print("after reverse : "); + list.print(); + } +} + +/* + to run the file : + javac reverse.java + java reverse + + results : + before : [ 5 8 1 7 2 ] + after reverse : [ 2 7 1 8 5 ] +*/ \ No newline at end of file