Tuesday 10 October 2017

Reversing a LinkedList using Stack in Java

Hello people, this is another blog dedicated to reversing a LinkedList using a Stack. Although it can be done in several ways like recursion, iteration, using constant auxiliary space, etc, 'Stack' is a very easy and efficient method to do the same.

This has been demonstrated in the code.


import java.util.*;

class TestClass {

static class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}

static Node head;
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
for(int i = 0; i < 10; i++) {
Node temp = new Node(i);
if(head == null) {
head = temp;
} else {
Node p = head;
while(p.next != null) {
p = p.next;
}
p.next = temp;
}
}
System.out.print("Printing the LinkedList: ");
Node x = head;
while(x != null) {
System.out.print(x.data + " ");
x = x.next;
}
System.out.println();

try {
Node p = head;
while(p != null) {
stack.push(p.data);
p = p.next;
}
System.out.print("Reversing the LinkedList using stack: ");
while(!stack.isEmpty()) {
System.out.print(stack.pop() + " ");
}
System.out.println();
} catch (EmptyStackException exception) {
System.out.println("The stack is Empty!");
}
}
}

People, please let me know if this could be improvised and let me know the concerns if any!

No comments:

Post a Comment