Upload
bzhar-omer
View
256
Download
2
Embed Size (px)
Citation preview
STACK
BZHAR OMER BAHRAM MUHAMMED BAZHDAR HAMAD
Erbil Technical Engineering CollegeInformation System Engineering
WHAT IS STACK?
Stack is modifying the array with a special algorithm called LAST IN FIRST OUT (LIFO)
We use this algorithm a lot , for example in the web browser
When you click on new page then pressing back button you return to the last website not the very first page
Stack Default methods
Push() = for adding new element
Pop() = for removing the last element
top() = for retrieving the last element
isEmpty() = condition if the stack is empty or not
Define array
Int array [ ] = new int [10];
Int pointer = -1;
-1
pointer 0 1 2 3 4 5 6 7 8 9
STACK METHODS , (isEmpty)
Boolean isEmpty() {
if (pointer < 0)
return True; //the stack is empty
else
return false;
}
STACK METHODS , (PUSH)
push (int a)
{
pointer++; //increment pointer by 1
array[pointer]=a; //adding value to last index }
a
pointer0 1 2 3 4 5 6 7 8 9
STACK METHODS , (POP)
pop() {
If(isEmpty())
System.out.println(“the stack is empty”);
else
array[pointer]=0;
pointer--; //decrement pointer by 1
}
a=0-1
pointer 0 1 2 3 4 5 6 7 8 9
Full program to implement stack in javapublic class stack {
static int array[]=new int [10];public static int pointer=-1;
public static boolean isEmpty(){
if(pointer<0)return true;
elsereturn false;
}public static void push(int a){
if(pointer==array.length)System.out.println("Stack is
full");else{pointer++;array[pointer]=a;}}
public static int top(){return array[pointer];
} public static void pop(){ if(isEmpty()) System.out.println("the stack is empty"); else{ System.out.println(array[pointer]+" removed"); array[pointer]=0; pointer--; }} static void print(int arr[]){ for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");} }public static void main(String[] args)
{//write push and pop the add print with
argument array to see whats going on}}