Thursday, 8 June 2017

Stack

Stack is a data structure that support Last In First Out . This implies that last element that is added to the data structure is extracted  first(LIFO )

Some of the important method of stack are as follows
1. Push: Method to add element to stack
2. Pop: Method to remove element from the stack
3. Peek: View the topmost element of the stack.

Below is the stack implementation using ArrayList.

package stack;

import java.util.ArrayList;

public class Stack {

private ArrayList<Object> stack = new ArrayList<>();

public Stack() {
super();
}

public Stack(ArrayList<Object> stack) {
super();
this.stack = stack;
}

/**
 * The method that add element to the top of the stack
 * 
 * @param o
 */
public void push(Object o) {
stack.add(o);
System.out.println("element added " + o);
}

/**
 * method that remove the element from top of stack
 */
public void pop() {

System.out.println("stack size " + stack.size());
// Ensure that we try to remove element from stack only when there is element in stack
// This condition is necessary to avoid null pointer exception
if (stack.size() > 0) {
System.out.println("element removed " + stack.get(stack.size() - 1));
stack.remove(stack.size() - 1);

else {
System.out.println("stack is empty");
}
}

/**
 * Method to check the topmost element of the stack
 * 
 * @return
 */
public Object peek() {
Object o = null;
// Ensure that we try to access element from stack only when there is element in stack 
// This condition is necessary to avoid null pointer exception
if (stack.size() > 0) {

o = stack.get(stack.size() - 1);
System.out.println("element at top " + o);

else {
System.out.println("stack is empty");
}

return o;

}

}

Test class
package stack;

public class MyStack {

public static void main(String[] args) {
Stack stack=new Stack();
stack.peek();
stack.push("A");
stack.push("B");
stack.push("C");
stack.peek();
stack.pop();
stack.peek();
stack.push("D");
stack.peek();
stack.pop();
stack.pop();
stack.pop();
stack.peek();
}


}

Output


element at top B
element added D
element at top D
stack size 3
element removed D
stack size 2
element removed B
stack size 1
element removed A
stack is empty
  


No comments:

Post a Comment

Streaming with Kafka API

The Kafka Streams API is a Java library for building real-time applications and microservices that efficiently process and analyze large-sca...