Dynamic Stack in Java

  • 0
Stack is one of the basic data structure in any programming language. In this article, I would try to make you understand stack and then, I would share a Java program that implements fixed size stack. Stack is the structure that implements last in first out elimination technique. A stack has two operations that can be operated on it. They are, push and pop. In push method, we put an item on the top of the top and pop operation removes the item currently one the top of the Stack.


I have implemented the Stack with interface. This interface is to be named as Stack.java
package ClassIllustration;

interface Stack
{
 void push(int item);
 int pop();
}
The source file named DynamicStackTest.java implements this interface.
package ClassIllustration;

class DynamicStack implements Stack
{
 int stack[];
 int top;
 
 DynamicStack(int size)
 {
  stack = new int[size];
  top=-1;
 }
 
 public void push(int node)
 {
  if(top==(stack.length-1))
  {
   int temp[] = new int[stack.length*2];
   int i;
   for(i=0;i<stack.length;i++)
   {
    temp[i]=stack[i];
   }
   stack=temp;
   stack[++top]=node;
  }
  else
   stack[++top]=node;
 }
 public int pop()
 {
  if(top==-1)
  {
   System.out.println("Stack is now empty");
   return 0;
  }
  else
   return (stack[top--]);
 }
 
 void display()
 {
  for(int i:stack)
  {
   System.out.println(i);
  }
 }
}
class DynamicStackTest
{
 public static void main(String...args)
 {
  DynamicStack fs = new DynamicStack(5);
  int i;
  for(i=0;i<20;i++)
  {
   fs.push(i);
  }
  System.out.println("Displaying contents of Stack");
  fs.display();
  System.out.println("Now popping elements off the stack");
  for(i=0;i<20;i++)
  {
   System.out.println("Popped element is " + fs.pop());
  }
 }
}

To compile the program
javac -d . Stack.java
javac -d . DynamicStackTest.java
And to run the program
java ClassIllustration.DynamicStackTest
Displaying contents of Stack
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Now popping elements off the stack
Popped element is 19
Popped element is 18
Popped element is 17
Popped element is 16
Popped element is 15
Popped element is 14
Popped element is 13
Popped element is 12
Popped element is 11
Popped element is 10
Popped element is 9
Popped element is 8
Popped element is 7
Popped element is 6
Popped element is 5
Popped element is 4
Popped element is 3
Popped element is 2
Popped element is 1
Popped element is 0

No comments:

Post a Comment