0% found this document useful (0 votes)
3 views

java1

The document contains Java code that implements two stack types: FixedStack and DynStack, both of which adhere to the IntStack interface. FixedStack has a fixed size, while DynStack dynamically resizes when full. The StackDemo class demonstrates pushing and popping elements from both stack types.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

java1

The document contains Java code that implements two stack types: FixedStack and DynStack, both of which adhere to the IntStack interface. FixedStack has a fixed size, while DynStack dynamically resizes when full. The StackDemo class demonstrates pushing and popping elements from both stack types.

Uploaded by

white Devil
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 3

package stack.

demo;
interface IntStack
{
void push(int item);
int pop();
}
class FixedStack implements IntStack
{
private int stack[];
private int tos;

FixedStack(int size)
{
stack = new int[size];
tos = -1;
}

public void push(int item)


{
if (tos == stack.length -1)
{
System.out.println("Stack is full.");
}
else
{
stack[++tos] = item;
}
}

public int pop()


{
if (tos <0)
{
System.out.println("Stack Underflow.");
return 0;
}
else
{
return stack[tos--];
}
}
}
class DynStack implements IntStack
{
private int stack[];
private int tos;

DynStack(int size)
{
stack = new int[size];
tos = -1;
}

public void push(int item)


{
if (tos == stack.length -1)
{
int temp[] = new int[stack.length *2];
for (int i=0;i<stack.length;i++)
{
temp[i]=stack[i];
}

stack = temp;
stack[++tos] = item;
}
else
{
stack[++tos]=item;
}
}

public int pop()


{
if(tos<0)
{
System.out.println("stack underflow");
return 0;
}
else
{
return stack[tos--];
}
}
}

class StackDemo
{
public static void main(String args[])
{
IntStack mystack;
DynStack ds = new DynStack(20);
FixedStack fs = new FixedStack(8);
mystack=ds;

for (int i=0; i<20;i++)


{
mystack.push(i);
}

mystack = fs;
for (int i =0;i < 8; i++)
{
mystack.push(i);
}
mystack = ds;
System.out.println("values in dynamic stack");
for (int i=0; i < 20; i++)
{
System.out.println(mystack.pop());
}
mystack = fs;
System.out.println("values in fixed stack");
for (int i=0; i<0; i++)
{
System.out.println(mystack.pop());
}
}
}

You might also like