import java.io.*;
import java.util.*;
class Stack
{
Object stk[];
int tos;
Stack(int capacity)
{
stk=new Object[capacity];
tos=-1;
}
void push(Object ob)
{
stk[++tos]=ob;
if(tos==stk.length)
{
System.out.println("stack overflow");
System.exit(0);
}
}
Object pop()
{
return(stk[tos--]);
}
void display()
{
for(int i=tos;i>=0;i--)
{System.out.print(stk[i]+" ");}
}
}
class Demo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(System.in);
System.out.println("enter number of elements to be pushed");
int c=sc.nextInt();
Stack s=new Stack(c);
Stack s1=new Stack(c);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(int j=0;j<c;j++)
{
System.out.println("enter element");
Object ob=br.readLine();
s.push(ob);
}
int mid=c/2;
System.out.println("displaying stack");
s.display();
System.out.println("");
System.out.println("poping middle elements from stack");
if(c%2==0)
{
while(s.tos!=mid)
{
Object t=s.pop();
s1.push(t);
}
Object t1=s.pop();
System.out.println(t1);
Object t2=s.pop();
System.out.println(t2);
}
else
{
while(s.tos!=mid)
{
Object t=s.pop();
s1.push(t);
}
Object t1=s.pop();
System.out.println(t1);
}
while(s1.tos!=-1)
s.push(s1.pop());
System.out.println("displaying stack");
s.display();
}
}
OUTPUT:(for odd number of elements)
enter number of elements to be pushed
9
enter element
1
enter element
2
enter element
3
enter element
4
enter element
5
enter element
6
enter element
7
enter element
8
enter element
9
displaying stack
9 8 7 6 5 4 3 2 1
poping middle elements from stack
5
displaying stack
9 8 7 6 4 3 2 1
OUTPUT:(for even number of elements)note:in even number middle two elements are poped
enter number of elements to be pushed
4
enter element
1
enter element
2
enter element
3
enter element
4
displaying stack
4 3 2 1
poping middle elements from stack
3
2
displaying stack
4 1
No comments:
Post a Comment