【问题标题】:Class and linked lists exercise in C++C++中的类和链表练习
【发布时间】:2020-08-22 03:16:24
【问题描述】:

所以我正在处理这段代码,实际上我已经完成了所有工作(除了我必须删除的代码中的一些不必要的部分)。这是一个处理堆栈和链表的 C++ 练习。该程序几乎可以正常工作,除了一点点。在我的switch语句的情况4中,当程序应该打印链表时,它会在打印完之后结束程序,而不是返回菜单供用户选择。我已经尝试并检查了所有内容,但它仍然可以。如果有人可以帮助我确定程序关闭的原因,我将不胜感激。

主文件

#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;
        }
    }
}

头文件

#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;
};

实现文件

#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;
        }
    }

}

【问题讨论】:

  • 您可以删除 nodeType *list; 私有成员,因为它目前未使用。另见Why is “using namespace std;” considered bad practice?。目前你只有coutendl 需要担心。 (您可以简单地删除 endl 并在字符串末尾添加 '\n'
  • 是的,这是我最终删除的为数不多的东西之一,因为我几乎将它改编为以前仅适用于链表的程序的堆栈。另外,谢谢你的建议,还有很多东西要学:)
  • 如果您仍有问题,请告诉我。但看起来你已经解决了。您可以添加的一个转折是使其成为一个双向链表,然后让nodeType *list 指向堆栈的底部,这样您就可以在反向(从 stackTop)和正向(从列表)方向上迭代堆栈内容。 (如果您需要该功能)

标签: c++ class stack


【解决方案1】:

看起来你处理退出循环很好,但我认为你的问题实际上是当你运行 printStack 函数时你的程序崩溃了。从代码中可以看出,堆栈中的底部元素(推送的第一个元素)将其 link 设置为 NULL,因为没有以前的元素可以链接到它(并且 stackTop 被初始化为 @ 987654325@)。这是一个问题,因为在 while 循环的下一次迭代中,curr 将是一个 NULL 节点,然后您尝试访问其 info 属性(这将创建未定义的行为,很可能以运行时错误/分段错误)。

您应该将printStack 函数更改为类似这样,以确保在到达NULL 节点后退出循环:

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
        }
    }

}

【讨论】:

  • 是的,就是这样,非常感谢您的解释!
  • @Java.exe 没问题
猜你喜欢
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 2015-01-02
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多