0

So I have this code I'm working on, I practically have it all done (save for some unnecessary pieces in the code I must remove). This is a C++ exercise dealing with stacks and linked lists. The program is pretty much working as it should except for one teeny bit. In case 4 of my switch statement, when the program is supposed to print the linked list, it will end the program after doing so, instead of going back to the menu for the user to choose. I've tried and checked everything, but it still does it. If someone could help me identify why the program is closing, I'd appreciate it.

main file

#include <iostream>
#include "Stacks.h"
using namespace std;

int main()
{
    //crear un menú para el usuario que vea las opciones para el stack
    Stack myStack;
    myStack.initializeStack();
    char answer;
    int x = 0;
    bool exit = false;

    while(!exit)
    {
        cout << "\nChoose option from menu: " << endl;
        cout << "1) Enter value into stack (push) " << endl;
        cout << "2) Remove last value from stack (pop) " << endl;
        cout << "3) See value at top of stack (top) " << endl;
        cout << "4) Print full stack " << endl;
        cout << "5) Exit program " << endl;
        cout << "Option: ";
        cin >> answer;

        switch(answer)
        {
            case '1':
                int item;
                cout << "\nEnter value to add to stack: ";
                cin >> item;
                myStack.push(item);
                break;

            case '2':
                myStack.pop();  
                break;

            case '3':
                x = myStack.top();
                if (!myStack.isEmptyStack())
                    cout << "\tTop value at stack: " << x << endl;
                break;

            case '4':
                myStack.printStack();
                exit = false;
                break;

            case '5':
                exit = true;
                break;

            default:
                cout << "Incorrect instruction" << endl;
                break;
        }
    }
}

header file

#include <iostream>
using namespace std;

struct nodeType
{
    int info;
    nodeType *link;
};


class Stack
{
    public:
        void initializeStack();
        bool isEmptyStack();
        bool isFullStack();
        void push(int);
        void pop();
        int top();
        void printStack();
        Stack();

    private:
        nodeType *stackTop;
        nodeType *list;
};

implementation file

#include <iostream>
#include "Stacks.h"
using namespace std;

void Stack::initializeStack()
{
    stackTop = NULL;
}

bool Stack::isEmptyStack() //verifica si el stack está vacío o no
{
    return (stackTop == NULL);
}

bool Stack::isFullStack() 
{
    return false; //lista encadenada no tiene límite
}

void Stack::push(int newItem) //añade un nodo al stack y le asigna el top
{
    nodeType *q;

    q = new nodeType;
    q->info = newItem;
    q->link = stackTop; //creaste un nodo nuevo y le pusiste el valor que enviaste
    //se pone stackTop en vez de Null para que la lista se pueda conectar

    stackTop = q; //pusiste el Top en el nodo
}

void Stack::pop() //remueve el top del stack
{
    if(!isEmptyStack())
        stackTop = stackTop->link; //mueves el top al nodo de abajo
    else
        cout << "\t<ERROR> Stack is empty. " << endl;
}

int Stack::top() //devuelve el top del stack
{
    if(!isEmptyStack())
        return stackTop->info;
    else
        cout << "\t<ERROR> Stack is empty." << endl;
}

void Stack::printStack()
{
    //imprime el top y de ahí va bajando
    if(isEmptyStack())
        cout << "<ERROR> Stack is empty." << endl;
    else
    {
        nodeType *curr;

        curr = stackTop;

        while(curr->info != 0)
        {
            cout << curr->info << "<-";
            curr = curr->link;
        }
    }

}
Java.exe
  • 1
  • 3
  • You can remove the `nodeType *list;` private member as it currently isn't used. Also see [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/q/1452721/364696). Currently you have only `cout` and `endl` to worry about. (which you can simply remove the `endl` and add `'\n'` at the end of your strings. – David C. Rankin May 07 '20 at 01:01
  • Yeah that's one of the few things I wound up removing, since I pretty much adapted this to stacks from a previous program which only worked with linked lists. Also, thanks for the advice, still got lots to learn :) – Java.exe May 08 '20 at 02:07
  • If you are still having issues, let me know. But it looks like you have it sorted out. A twist you could add is make it a doubly-linked list and then let `nodeType *list` point to the bottom of the stack so you could iterate over the stack contents in both reverse (from stackTop) and forward (from list) directions. (if you need that capability) – David C. Rankin May 08 '20 at 02:31

1 Answers1

0

It seems that you're handling exiting the loop just fine, but I think your issue is actually that your program is crashing when you run the printStack function. As you can tell from your code, the bottom element in your stack (the first element pushed) will have its link set to NULL since there are no previous elements to link it to (and stackTop is initialized to NULL). This is an issue because in the next iteration of the while loop, curr will be a NULL node, and then you are trying to access its info property (which will create undefined behavior, most likely in the form of a runtime error/segmentation fault).

You should change your printStack function to something like this to ensure that you exit the loop once you have reached a NULL node:

void Stack::printStack()
{
    //imprime el top y de ahí va bajando
    if(isEmptyStack())
        cout << "<ERROR> Stack is empty." << endl;
    else
    {
        nodeType *curr;

        curr = stackTop;

        while(curr) // check if curr is not NULL and break when it is
        {
            cout << curr->info << "<-";
            curr = curr->link; // if curr->link is NULL, then curr will be NULL in the next iteration
        }
    }

}
awarrier99
  • 3,628
  • 1
  • 12
  • 19