c++ - 在 C++ 中显示堆栈元素时无限循环

标签 c++ data-structures stack

我写了一个栈数据结构的程序。 它在显示堆栈元素时显示错误。当堆栈有超过 2 个值时调用显示函数时开始无限循环

#include <iostream>
#include <string>

using namespace std;

节点类

class Node
{
public:
    int data;
    Node *previous;
};
class Stack
{
private:
    Node* head,start;
public:
    Stack();
    Node* getNode();
    void parseValue();
    void push(Node *);
    void display();
};

栈类

Stack::Stack()
{
    head = NULL;
}
void Stack::parseValue()
{
    char choice;
    Node *newNode = NULL;
        while (1)
        {
            cout << "Enter Data in the List (Enter N to cancel) ";
            cin >> choice;
            if (choice == 'n' || choice == 'N')
            {
                break;
            }
            newNode = getNode();
            push(newNode);
        }
    }

int main()
{
    Stack a;
    a.parseValue();
    a.display();

}

最佳答案

试试这个。

#include <iostream>
#include <string>

using namespace std;

class Node
{
public:
    int data;
    Node *previous;
};
class Stack
{
private:
    Node *head, *start;
//    Node* head,start; // This is same with "Node start, *head";
public:
    Stack();
    Node* getNode();
    void parseValue();
    void push(Node *);
    void display();
};

Stack::Stack()
{
    head = NULL;
}
Node *Stack::getNode()
{
    Node *temp = new Node;
    cin >> temp->data;
    temp->previous = NULL;
    return temp;
}
void Stack::parseValue()
{
    char choice;
    Node *newNode = NULL;
        while (1)
        {
            cout << "Enter Data in the List (Enter N to cancel) ";
            cin >> choice;
            if (choice == 'n' || choice == 'N')
            {
                break;
            }
            newNode = getNode();
            push(newNode);
        }
    }

void Stack::push(Node* newNode)
{
    if(head == NULL)
    {
        head = newNode;
        cout << newNode->data << " added to stack" << endl;
    }
    else
    {
        // change sequencs to this
        newNode->previous = head;
        head = newNode;

        /*
        head = newNode; // if you do this first,
        newNode->previous = head; // then newNode becomes head node
        // and results like this: head->previous = head,
        // so head->head->head->...
        */
    }

}

void Stack::display()
{
    if(head == NULL)
    {
        cout << "No data in the stack to display.";
    }
    else
    {
        Node * temp = head;
        while(temp != NULL) // changed; you should check temp's state because it points the ndoe you want
        {
            cout << temp->data << "\t";
            temp = temp->previous;
        }
    }
}
int main()
{
    Stack a;
    a.parseValue();
    a.display();
    return 0; // it is better to end main with return statement
}

编辑:

这是更好的堆栈模型。试试吧。

#include <iostream>
using namespace std;

// I don't know what you learned, so I'll try
//  to explain my code as easy as possible.

// define stack's status constant
const int STACK_IS_EMPTY = -1; // -1 or whatever you want

// Node
// If you learned C++ template, replace it with that
class Node {
    // It is better to encapsulate member variable(field)
    // than to let fields in pulic
    int _data;
    Node *_next;
public:

    // constructor
    // * advice: try to find 'member initializer'
    Node(int data) {
        _data = data;
    }
    /* same constructor written with member initializer
    Node(int data): _data(data) {}
    */

    // member getter & setter method to encapsulation
    int data() { return _data; }
    void setData(int data) { _data = data; }
    Node *next() { return _next; }
    void setNext(Node *next) { _next = next; }
};

// Stack
class Stack {
    // fields
    Node *head;

public:
    Stack(); // constructor
    ~Stack(); // destructor
    // push and pop functions are stack basic functions
    void push(int data);
    int pop();
    // convenient functions
    bool is_empty(); // return true when stack is empty, false when not
    int top(); // return stack's top node data
};

// constructor
Stack::Stack() {
    // * advice: C++11 or higher supports nullptr keywords; try this after
    // head = nullptr;
    head = NULL;
}

void Stack::push(int data) {
    // make new node
    Node *newNode = new Node(data);

    if (is_empty() == true) { // if stack is empty
        head = newNode;
    }
    else { // stack is not empty
        newNode->setNext(head);
        head = newNode;
    }
}
int Stack::pop() {
    if (is_empty() == true) {
        return STACK_IS_EMPTY;
    }
    Node *delNode = head;
    head = delNode->next();
    int data = delNode->data();
    delete delNode;
    return data;
}

// convenient functions
bool Stack::is_empty() {
    return (head == NULL);
}
int Stack::top() {
    if (head == NULL) {
        return STACK_IS_EMPTY;
    }
    return head->data();
}

// destructor
Stack::~Stack() {
    // you must deallocate dynamically allocated object
    // if you don't do this, it results to serious leak of memories

    if (is_empty() == true) { // if stack is empty
        return; // just return
    }

    // deallocate all nodes
    while (is_empty() == false) { // while stack is not empty
        pop(); // keep popping
    }
}

// Demonstration of stack usage
int main() {
    int input;
    Stack stack;

    while (true) { // keep getting input number and pushing it into stack
        cout<<"Enter natural number (0 when quit): ";
        cin>>input;

        if (input == 0) { // when quit number has entered
            break; // quit
        }

        stack.push(input);
    }

    while (stack.is_empty() == false) { // while stack is not empty
        int data = stack.pop(); // pop stack's node and get it's data
        cout<<data<<endl; // print it
    }

    return 0;
}
  • 我的母语不是英语,所以我会说奇怪的句子..

关于c++ - 在 C++ 中显示堆栈元素时无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29471541/

相关文章:

c++ - 数据结构中的 MST 和唯一性问题已解决 Ex?

C++ 引用类型推荐用法

c++ - 从 map 中检索后 map 中的对象损坏

c++ - vc++ - 套接字没有写入端口

c - 为单链表编写适当的push() 函数。

java - 如何更改所使用的房间

c - C 段错误中的大型阵列,erathos 的 Sievs

c - 使用链表将数据插入堆栈

c - fread()、solaris 到 unix 的可移植性和未初始化值的使用

c++ - 如何使用输入/输出运算符大声朗读 C++ 表达式?