Posted by: Sourav | April 21, 2015

Dynamic Stack,size doubled after being initialized with a fixed size


import java.io.*;
class Stack{
int stck[]=new int[10];
int tos;
int[] resize(int arr1[])
{
int temp[]=new int[2*arr1.length];
System.arraycopy(arr1,0,temp,0,10);
arr1=temp;
return arr1;
}
Stack(){
tos=-1;
}
void push(int item)
{
if(tos==(stck.length-1))
{
System.out.println(“Stack full and thus resizing”);
stck=resize(stck);
}

stck[++tos]=item;
System.out.println(“The stack length is now “+stck.length);
System.out.println(“Number of items in stack = “+(tos+1));
}

int findlength()
{
return tos;
}
int pop()
{
if (tos<0)
{
System.out.println(“Stack Underflow”);
return 0;
}
else
return stck[tos–];
}
}
class Test{
public static void main(String args[]) throws Exception
{
char ch=’y’;
int count=0;
Stack mystack1=new Stack();

Stack mystack2=new Stack();

while(true)
{
System.out.println(“Want to populate the stack?”);
InputStreamReader s=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(s);
ch=(br.readLine()).charAt(0);
if(ch==’n’)
break;
System.out.println(“Number Please”);
s=new InputStreamReader(System.in);
br=new BufferedReader(s);

mystack1.push(Integer.parseInt(br.readLine()));

}
int len=mystack1.findlength();
for(int i=0;i<len;i++)
{
System.out.println(“The “+ i + ” element is “+mystack1.pop());
}

}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: