Linked Stack

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Kindle Life
    New Member
    • Dec 2018
    • 1

    Linked Stack

    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<iostre am.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.Deleti on";
    cout<<"3.Displa y";
    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');
    }
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    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


    Code:
    int push(stack* node, int data);
    etc for the other functions.

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

    This is a typical list:

    Code:
    struct list
    {
    
       stack* top;   /*start of list */
       stack* end;   /* end of list */
       stack* current; /* the current position in the list.
    };

    Now you can create a list:


    Code:
    list* theList = create();
    this function creates the list on the heap and sets all the member pointers to zero.

    Now you can:

    Code:
    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.

    Comment

    Working...