Thursday 1 August 2019

Reverse the elements of stack


This is continuation to my previous post, In my previous post, I explained how to add an element to the end of stack. I am going to use the same function 'insertAtEnd' to reverse the elements of stack.

Approach is like below.

Recursively pop the elements of stack, whenever you reach the end of stack, add the popped elements one by one to the end of stack.

Find the below working application.

MyStack.java
package com.sample.collection;

import java.util.Iterator;
import java.util.Stack;

public class MyStack<T> extends Stack<T> {

 private static final long serialVersionUID = 1L;

 private T elementToBeInserted;

 public void insertAtEnd(T ele) {
  elementToBeInserted = ele;
  insertAtEnd();
 }

 private void insertAtEnd() {
  if (this.isEmpty()) {
   this.push(elementToBeInserted);
   return;
  }
  T ele = this.pop();
  insertAtEnd();
  this.push(ele);
 }

 public void reverseStack() {
  if (this.isEmpty()) {
   return;
  }

  T ele = this.pop();
  reverseStack();
  this.insertAtEnd(ele);
 }

 public void printStackElements() {
  Iterator<T> iter = this.iterator();

  System.out.println("Elements in the stack are");
  System.out.println("--------------------------------");
  while (iter.hasNext()) {
   System.out.println(iter.next());
  }
  System.out.println("--------------------------------");
 }
}


Application.java
package com.sample.app;

import com.sample.collection.MyStack;

public class Application {

 public static void main(String args[]) {
  MyStack<Integer> myStack = new MyStack<>();

  myStack.insertAtEnd(1);
  myStack.insertAtEnd(2);
  myStack.insertAtEnd(3);
  
  myStack.printStackElements();
  
  System.out.println("Reversing the stack");
  
  myStack.reverseStack();
  myStack.printStackElements();
  
 }
}

Output
Elements in the stack are
--------------------------------
3
2
1
--------------------------------
Reversing the stack
Elements in the stack are
--------------------------------
1
2
3
--------------------------------

You may like





No comments:

Post a Comment