Thursday, 1 August 2019

Add element to the end of stack


One of interviewer asked me to add an element to the end of stack using recursion.

I approached the problem like below.

Traverse the stack till the end by popping the elements of stack, once I reach the stack, I inserted the element, after that my logic will push previous elements of the 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.peek();
  this.pop();
  insertAtEnd();
  this.push(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.printStackElements();

  myStack.insertAtEnd(2);
  myStack.printStackElements();

  myStack.insertAtEnd(3);
  myStack.printStackElements();
  
  
 }
}

You may like



No comments:

Post a Comment