Monday, 2 December 2013

STACK


     A Stack is a linear list of elements in which insertion and deletions can takes place from only one end called top of the stack.
A common example of stack is a collection of trays on which the operations can be performed by inserting and deleting the new tray from top end only.
PUSH operation: The insertion operation on the stack is called PUSH operation.
POP operation: The deletion operation from the stack is called POP operation.
    The insertion and deletion can be done by only at the top of the stack.
Initially top =-1 , when the STACK is empty. And when we PUSH new elements into the STACK (12,13,14) then top=2.
When we pop two elements from the STACK, then top=0.
1) STACK OVERFLOW: It is the situation where, there is no place in the STACK to perform PUSH operation.
2) STACK UNDERFLOW: It is the situation where, the STACK is empty and we cannot POP elements from the STACK.

The Operations which can be performed on STACK are:
1) PUSH: Adding an element into the STACK
2) POP: Removing an element from the STACK
3) DISPLAY : Showing all elements which are present in the STACK
JAVA PROGRAM implementing STACK operations 


import java.util.Scanner;

class Stack {

int[] a;
int top;

public Stack(int n) {
a = new int[n];
top = -1;
}

public void push(int val) {
if (top == a.length - 1) {
System.out.println("Stack overflow...");
} else {
top++;
a[top] = val;
}
}

public void pop() {
if (top == -1) {
System.out.println("Stack underflow...");
} else {
System.out.println("Element popped" + a[top]);
top--;
}
}

public void display() {
if (top == -1) {
System.out.println("Stack empty...");
} else {
for (int i = top; i >= 0; i--) {
System.out.println("Stack element: " + a[i]);
}
}
}
}

public class UseStack {

static public void main(String args[]) {
Scanner sc = new Scanner(System.in);
Stack s;
int n;
System.out.println("Enter the size of the stack: ");
n = sc.nextInt();
s = new Stack(n);
int choice;

do {
System.out.println("1.PUSH" + "\n" + "2.POP" + "\n" + "3.DISPLAY" + "\n" + "0.EXIT");
System.out.println("Enter your choice");
choice = sc.nextInt();

switch (choice) {
case 1:
int value;
System.out.println("Enter element to push");
value = sc.nextInt();
s.push(value);
break;

case 2:
s.pop();
break;

case 3:
s.display();

case 0:
break;

default:
System.out.println("invalid choice...");
}
} while (choice != 0);

}
}


No comments:

Post a Comment

java binary tree program for inorder, preorder, postorder

import java.util.Queue; import java.util.LinkedList; public class TreeTraverse { private static class Node<T> { public Node<T> ...