So thought of training with some stack in the beginning of algorithms. I'm gonna use java for the coding.
So as the word says its a stack, like a stack of plate. what is special about it is how the elements come in and out of it. The first plate to come in is the first plate to get out. we call this Fist In First Out (FIFO). Without further ado lets go straight in to the code.
The first thing I created was the stack. Here in Class StackA I initially defined the array, array size and the top element.
So this may not be very difficult to understand but I have defined two methods namely pop and push in the code.
Push is the method that you simply place an element in the top of the satck and pop is the method where you remove the top element in the stack. (Popping it out).
So lets see some other functions later.
So as the word says its a stack, like a stack of plate. what is special about it is how the elements come in and out of it. The first plate to come in is the first plate to get out. we call this Fist In First Out (FIFO). Without further ado lets go straight in to the code.
The first thing I created was the stack. Here in Class StackA I initially defined the array, array size and the top element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | public class StackA { private int MaxSize; // size of the stack private int[] arr; // the stack private int top; // the top element public StackA(int s){ // constructor initiate stack MaxSize = s; // assign the size arr = new int[s];//creating the stack top = -1; // initial top element } public void push(int k){ arr[++top] = k; //pre incrementing top, post incrementing will give ArryOutOfBoundException } public void pop(){ System.out.println(arr[top--]); } public static void main(String[] args) { StackA A = new StackA(4); //creating object A.push(3); //pushing 3 to the top System.out.println("pop the top element"); A.pop(); //pop the top element } } |
So this may not be very difficult to understand but I have defined two methods namely pop and push in the code.
Push is the method that you simply place an element in the top of the satck and pop is the method where you remove the top element in the stack. (Popping it out).
So lets see some other functions later.