The following program contains code, how to write a stack data structure for an integer datatype.
public class IntegerStack {
public static void main(String []a) {
Elements e = new Elements () ;
e.push (50) ;
e.push (500) ;
e.push (150) ;
e.pop();
e.push(10);
e.pop();
e.push (100);
e.pop();
e.pop();
e.pop();
e.pop();
}
}
class Elements {
int stackArray[] = new int[5] ;
int i = 0;
public void push (int num) {
if (i < 5) {
stackArray[i] = num;
i++;
System.out.println ("Stack contains :");
for (int a = 0; a < i; a++)
System.out.println(stackArray[a]);
}
else
System.out.println("Stack is full.");
}
public void pop () {
if (i > 0) {
int remNum = stackArray[i] ;
i--;
System.out.println ("Stack contains :");
for (int a = 0; a < i; a++)
System.out.println(stackArray[a]);
}
else
System.out.println("Stack is empty.");
}
}
No comments:
Post a Comment