Tuesday, November 6, 2007

Stack Using Array

Program : Stack Using Array



import java.io.*; // importing input/output package


class stacks // class definition


{

int data[]=new int[10]; // initializing array

int top,i=0;

int n=0; // initializing variables


stacks() // constructor


{

top=-1; // initializing top variable

n=10;

}


void create(int item) // create function


{

if (top>n) // conditional statement

{

System.out.print("OVERFLOW"); // print statement

return;

}

else

{

top=top+1; // incrementing top

data[top]=item;

}

}


void pop() // print statement


{

if (top==-1)

{


System.out.print("EMPTY"); // print statement

return;

}

else

{

System.out.print(data[top]);

top=top-1; // decrementing top

}

}


void display() // display function


{

for(i=top;i>-1;i--) // looping structure

{

System.out.println("|_\t"+data[i]+"\t_|");

}

if (top==-1)

{

System.out.println("EMPTY"); // print statement

}

}

}






class stack


{

public static void main(String args[]) throws IOException

// main function

{

int x,y,z,d,p;

DataInputStream a=new DataInputStream(System.in);

// invoking input class

stacks t=new stacks(); // object decleration

int exit=0;

while (exit==0)

{

System.out.println("\t\t\nMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.QUIT");

System.out.println("Enter your choice:");

x=Integer.parseInt(a.readLine()); // converting input received to integer


switch (x) // switching cases

{


case 1:

{

System.out.println("ENTER ELEMENT:");

p=Integer.parseInt(a.readLine());

t.create(p); // calling create function

}

break;





case 2:


{

y=0;

t.pop(); // calling pop function

}

break;




case 3:


{

t.display(); // calling display function

}

break;




case 4:


{

exit=1; // exit program

}

break;

}

}

}

}

0 comments: