8
STACK BZHAR OMER BAHRAM MUHAMMED BAZHDAR HAMAD Erbil Technical Engineering College Information System Engineering

Java Data Structure - Stack

Embed Size (px)

Citation preview

Page 1: Java Data Structure - Stack

STACK

BZHAR OMER BAHRAM MUHAMMED BAZHDAR HAMAD

Erbil Technical Engineering CollegeInformation System Engineering

Page 2: Java Data Structure - Stack

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

Page 3: Java Data Structure - Stack

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

Page 4: Java Data Structure - Stack

Define array

Int array [ ] = new int [10];

Int pointer = -1;

-1

pointer 0 1 2 3 4 5 6 7 8 9

Page 5: Java Data Structure - Stack

STACK METHODS , (isEmpty)

Boolean isEmpty() {

if (pointer < 0)

return True; //the stack is empty

else

return false;

}

Page 6: Java Data Structure - Stack

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

Page 7: Java Data Structure - Stack

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

Page 8: Java Data Structure - Stack

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}}