Friday, 16 January 2015

Data Structures - Java Program to implement stack operations


In this post we will see some basic operations of stack like insertion , deletion . Generally a stack is a an abstract data type where insertion and deletion takes place at one end and that end is know as top.

Inserting an item to stack is called as PUSH operation.
Removing an item from a stack is called as POP operation.

Inserting or deleting an item takes place at one end and they are done one by one.

See the image below,
Data stack.svg
"Data stack" by User:Boivie - made in Inkscape, by myself User:Boivie. Based on Image:Stack-sv.png, originally uploaded to the Swedish Wikipedia in 2004 by sv:User:Shrimp. Licensed under Public Domain via Wikimedia Commons.

The principle of the stack is : Last In First Out (LIFO)
Here in this program we initially take top as -1 and when an element is inserted top is incremented and pushes the value in stack , similarly when when an element is deleted top is decremented and pops the value from stack.

There are two error conditions here :
  1. Stack Overflow
  2. Stack Underflow
Stack Overflow is a situation where the stack is full and we still trying to insert elements to that stack.
Stack Underflow is a situation where the stack is empty and we are still trying to delete  elements from that stack.

PROGRAM :
package codingcorner.in;

import java.util.Scanner;

public class StackOperations {
static final int MAX = 10;
static int top = -1;
static int stack[] = new int[MAX];

public static void main(String[] args) {
int element, choice, d;
Scanner scan = new Scanner(System.in);

while (true) {
System.out.print("\nSTACK OPERATIONS \n\n");
System.out.print("1.Insert \n");
System.out.print("2.Delete \n");
System.out.print("3.Display \n");
System.out.print("4.Exit\n\n");
System.out.print("Enter your choice. \t");
choice = scan.nextInt();

switch (choice) {
case 1:
if (top == MAX - 1)
System.out
.print("\nSTACK is already full. Delete some elements and try again ! \n ERROR : STACK OVERFLOW\n");
else {
System.out.print("\nEnter the value to insert.\t");
element = scan.nextInt();
push(element);
}
break;
case 2:
if (top == -1)
System.out
.print("\nSTACK is already empty. \n ERROR : STACK UNDERFLOW\n");
else {
element = pop();
System.out.println("Element removed from stack is "+ element);
}
break;
case 3:
if (top == -1)
System.out
.print("\nSTACK is empty. Cannot display anything\n");
else {
System.out.println("There are " + (top + 1)+ " elements in stack.");

for (d = top; d >= 0; d--)
System.out.println(stack[d]);
System.out.print("\n");
}
break;
case 4:
return;
}

}
}

private static int pop() {
int element;
if (top == -1)
return top;

element = stack[top];
top--;

return element;
}

private static void push(int value) {
top++;
stack[top] = value;

}
}

OUTPUT : 
Java - Stack Operations
Java - Stack Operations


Java - Stack Operations
Java - Stack Operations

No comments:

Post a Comment