when the program is executed there are 4 options
a: push
b: pop
c: view stack
d: exit
all of them are working fine according to what they are supposed to do.
but the problem is that i am getting 0(zero) at the last node of my linked stack.
for example:-
if i choose option 'a' to push items(say 1,2,3) onto stack.
but when i choose option c to view the elements stored in stack.
i get the items as follows:
3
2
1
0
3 2 1 is fine but why i am getting 0(zero) at last.
also when i apply pop operation
it first gives me the items that i have entered but again i get 0(zero) at last.
but after when i poped out the 0 from my stack.
then there is no zero (i mean zero can be poped out like other elements and after that it will be no longer in stack)
and finaly i get my stack without zero
now if i again enter some elements(say 7,6,4)
and then view the stack by choosing option c
then i get what i had entered
i.e
7
6
4
and at last there is no zero
so my question is
why i am initialy getting 0 as last element in my stack?
also i am using turboc v 3.0
here is the code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include<iostream.h>
#include<conio.h>
struct node
{
int info;
node *link;
};
class lstack
{
node *top;
public:
lsatck(){top=0;}
void push();
int pop();
int isempty(){
if(top==0)
return(1);
else
return(0);
}
void display();
};
void main()
{
int exit=0;
class lstack st;
char ch;
clrscr();
while(!exit){
cout<<"\na: PUSH\nb: POP\nc: View Stack\nd: Exit\n";
ch=getch();
switch(ch)
{
default:
cout<<"\ninvalid option";
break;
case 'a':
st.push();
break;
case 'b':
if(st.isempty())
cout<<"\nUnderflow\n";
else
cout<<"\nitem="<<st.pop();
break;
case 'c':
st.display();
break;
case 'd':
exit=1;
}
}
getch();
}
void lstack ::push()
{
node *newnode;
newnode=new node;
int item;
cout<<"\nEnter item\t";
cin>>item;
newnode->info=item;
newnode->link=top;
top=newnode;
}
int lstack ::pop()
{
node *del_node;
int temp;
del_node=top;
top=top->link;
temp=del_node->info;
delete del_node;
return(temp);
}
void lstack ::display()
{
node *ptr=top;
while(ptr!=0)
{
cout<<endl<<ptr->info;
ptr=ptr->link;
}
}
|