Problem statement:
Stack data structure implementation in java.
Stack data structure implementation in java.
- public class Stack {
- static final int max = 15;
- int top;
- int a[] = new int[max];
- boolean push(int x) {
- if (top >= (max - 1)) {
- System.out.println("stack overflow");
- return false;
- } else {
- a[++top] = x;
- System.out.println(x + " pushed into stack");
- return true;
- }
- }
- int pop() {
- if (top < 0) {
- System.out.println("stack underflow");
- return 0;
- } else {
- int x = a[top--];
- return x;
- }
- }
- int size() {
- return top + 1;
- }
- boolean isEmpty() {
- return top == -1;
- }
- boolean isFull() {
- return (top == (max - 1));
- }
- int peak() {
- if (!isEmpty())
- return a[top];
- else return -1;
- }
- Stack() {
- top = -1;
- }
- }
- class MainExecution {
- public static void main(String[] args) {
- Stack s = new Stack();
- s.push(10);
- s.push(20);
- s.push(30);
- System.out.println("size: " + s.size());
- s.push(25);
- System.out.println("new size: " + s.size());
- System.out.println(s.pop() + " popped from stack");
- System.out.println("top element is peak: "+s.peak());
- }
- }
Output:
10 pushed into stack
20 pushed into stack
30 pushed into stack
size: 3
25 pushed into stack
new size: 4
25 popped from stack
top element peak: 30
No comments:
Post a Comment