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();
}

FixedStackTest.java implemmts this interface.
package InterfaceIllustration;

abstract class Rectangle implements Figure
{
 public int area(int length, int breadth)
 {
  return (length*breadth);
 }
}
class Square extends Rectangle
{
 public int perimeter(int...side)
 {
  int per = 0;
  for(int i:side)
   per = per + i;
  return per;
 }
}
class IncompleteTest
{
 public static void main(String...args)
 {
  Square sq = new Square();
  System.out.println("Area of the square with length 4 and breadth 4 is " + sq.area(4,4));
  System.out.println("Perimeter of square is " + sq.perimeter(4,4,4,4));
 }
}
To compile the program
javac -d . Stack.java
javac -d . FixedStackTest.java
And to run the program
java ClassIllustration.FixedStackTest
Here is the sample output of the program
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Now popping elements off the stack
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