423,846 Members | 2,048 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 423,846 IT Pros & Developers. It's quick & easy.

Linked Stack

P: 1
Just the if function executes in the functions and does'nt go to the next condition below the if condition.
What could have possibly gone wrong?

#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>
struct stack
{
int info;
stack *next;
};
stack *top=NULL;

void push()
{
int data;
cout<<"Enter data";
cin>>data;
//create a new node
stack*ptr=new stack;
ptr->info=data;
ptr->next=top;
}
void pop()
{
stack *ptr;
//empty
if(top==NULL)
{
cout<<"Stack empty";
return;
}
ptr=top;
cout<<ptr->info;
top=ptr->next;
delete ptr;
}

void display()
{
if(top==NULL)
{
cout<<"Stack empty";
return;
}
stack *ptr=top;
while(ptr!=NULL)
{
cout<<ptr->info;
ptr=ptr->next;
}
}

void main()
{
int op;
char cnt;
do
{
cout<<"1.Insert";
cout<<"2.Deletion";
cout<<"3.Display";
cout<<"4.Exit";

cout<<"Enter the choice";
cin>>op;
switch(op)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
case 4: exit(0);
}
cout<<"Do you wanna continue ?";
cin>>cnt;
}
while(cnt=='Y'||cnt=='y');
}
1 Week Ago #1
Share this Question
Share on Google+
1 Reply


weaknessforcats
Expert Mod 5K+
P: 9,196
First thing is to remove data entry from the push() function. You call push using the data. It's not the job of push() to come up with the data.


You also need to supply the address of the stack variable you are going to se to push the data


Expand|Select|Wrap|Line Numbers
  1. int push(stack* node, int data);
  2.  
etc for the other functions.

Also missing is the list itself. The code just uses node values

This is a typical list:

Expand|Select|Wrap|Line Numbers
  1. struct list
  2. {
  3.  
  4.    stack* top;   /*start of list */
  5.    stack* end;   /* end of list */
  6.    stack* current; /* the current position in the list.
  7. };

Now you can create a list:


Expand|Select|Wrap|Line Numbers
  1. list* theList = create();
this function creates the list on the heap and sets all the member pointers to zero.

Now you can:

Expand|Select|Wrap|Line Numbers
  1. AddToEnd(list* thelist, int data);

The user of the list does not know about the nodes. The user just creates the list and adds a value too the end of the list. The AddToEnd function creates the stack variable and places the data in the info member. The function also adjust the pointers in the list struct as necessary.

Start with main() and code what you want the user to do. Then write the functions to do it. Try to get a design in place before you actually start coding.
1 Week Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.