Implement Stack Using Array - The Coding Shala
Home >> Data Structures >> Implement Stack Using Array
Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
In this post, we will learn how to Implement Stack Using Array and will write a Java program for the same.
Implement Stack Using Array
We will implement Stack's operations using an array. If we use an array then it is easy to implement but the size limit is there.
Java Program:
class MyStack { static final int MAX = 1000; int top; int a[]; boolean isEmpty() { return (top < 0); } MyStack() { top = -1; a = new int[MAX]; } void push(int x) { if (top >= (MAX - 1)) { //stack overflow //return false or print error } else { a[++top] = x; } } int pop() { if (top < 0) { //stack underflow return -1; } else { int x = a[top--]; return x; } } int peek() { if (top < 0) { //stack underflow return -1; } else { int x = a[top]; return x; } } }
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment