0 votes
267 views
in Data Structure And Algorithm by (3.7k points)
implement a stack using array in java.

1 Answer

0 votes
by (5k points)

As we know that, Stack is a linear data structure. It follows a particular order in which the operations are performed. The stack follows LIFO(Last In First Out) or FILO(First In Last Out) order.

There are following three basic operations are performed in the stack:-

  • Push: Push() method adds an item in the stack. If the stack is full, then it will throw an exception like Stack Overflow condition.
  • Pop: Pop() method removes an item from the stack. When you popped the items in stack you will get that items in the reversed order in which they are pushed. If stack is empty, then it will throw an exception like Stack Underflow condition.
  • Peek or Top: Peek() method returns top element of stack.
  • isEmpty: isEmpty() method returns true if the stack is an empty, else return false.
See the following running code to implement stack using array:- 
public class StackUsingArrayTest {
public static void main(String[] args) {
StackUsingArray stack = new StackUsingArray();
System.out.println("Stack Size: "+stack.getSize());
stack.push(10);
stack.push(20);
stack.push(30);
// stack.push(40);
System.out.println("Stack Size: "+stack.getSize());
System.out.println(stack.pop());
System.out.println("Stack Size: "+stack.getSize());
System.out.println(stack.peek());
System.out.println("Stack Size: "+stack.getSize());
}
}
public class StackUsingArray {
int arr[],top=-1, capacity=0;
public StackUsingArray() {
this.capacity = 3;
arr = new int[capacity];
}
public StackUsingArray(int capacity) {
this.capacity = capacity;
arr = new int[capacity];
}
//Time Complexity O(1)
public void push(int data) {
if(top+1 == capacity) {
throw new RuntimeException ("Stack Overflow");
}
top++;
arr[top] = data;
}
//Time Complexity O(1)
public int pop() {
if(top == -1) {
throw new RuntimeException ("Stack Underflow");
}
int data = arr[top];
top--;
return data;
}
//Time Complexity O(1)
public int peek() {
if(top == -1) {
throw new RuntimeException ("Stack Underflow");
}
return arr[top];
}
//Time Complexity O(1)
public int getSize() {
int size = 0;
if(top>-1) {
size = top+1;
}
return size;
}
//Time Complexity O(1)
public boolean isEmpty() {
if(top>-1) {
return true;
}
return false;
}
}
Output:-
Stack Size: 0
Stack Size: 3
30
Stack Size: 2
20
Stack Size: 2

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...