【问题标题】:Stack will only display first value?堆栈只会显示第一个值?
【发布时间】:2013-12-12 07:50:59
【问题描述】:

我正在尝试使用动态分配的链表制作一个堆栈程序,我对整个事情感到非常困惑。无论如何,我制作了自己的堆栈结构,但它只显示第一个元素。这是我的 main.cpp 文件:

// (Description in Word File)

#include "Prototypes.h"

unsigned seed = time(0);

int main()
{
    int random; // score between 30 and 95

    Stack stk; // stack of random scores

    srand(seed);

    // Populate that stack!
    for (int count = 0; count != 20; count++)
    {
        // generate a random number between 30 and 95
        random = (95 - (rand() % 65)) + 1;
        stk.push(random);

        // just to check for values
        //cout << stk.lst.getFirst() << endl;
    }

    // now display
    stk.lst.print();

    return 0;
}

文件中用到的函数如下:

int List::getFirst() const{
    return first->data;}

void List::addFirst(int value)
{
    Node* tmp = new Node(value);
    first = tmp;
}

void Stack::push(int value){
    lst.addFirst(value);}

void List::print() const
{
    Node* cur = first;

    cout << "\tValues:\n\n";

    for (int count = 1; cur != nullptr; count++)
    {
        cout << " " << cur->data;

        // print in rows of 5
        if ( (count % 5) == 0)
            cout << endl;

        // move down the list
        cur = cur->next;
    }

    cout << endl << endl;
}

最后,这是我使用的结构:

struct Node
{
    int data;
    Node* next;

    Node(int value) : data(value), next(nullptr){}
};

struct List
{
    Node* first; // a pointer to the first Node
    List() : first(nullptr){}

    void addFirst(int);

    int getFirst() const;

    bool removeFirst();

    void addLast(int);

    int getLast() const;

    bool removeLast(); 

    void print() const;
};

struct Stack
{
    List lst;

    void push(int);

    int pop();

    bool isEmpty() const;
};

有人可以向我解释为什么只显示一个值吗?请简单点,我是编程新手。谢谢!

【问题讨论】:

    标签: c++ linked-list stack structure dynamic-memory-allocation


    【解决方案1】:
    void List::addFirst(int value)
    { 
        Node* tmp = new Node(value);
        /* without the next line, you throw away the old first node. */
        tmp->next = first;
        first = tmp;
    }
    

    【讨论】:

    • 是的!欢迎来到 SO;这里习惯于在解决您的问题的答案上打勾,以向搜索类似问题的人表明它是正确的。另外,我得到了代表=D。
    猜你喜欢
    • 2014-08-27
    • 1970-01-01
    • 2021-11-19
    • 2020-11-29
    • 2012-07-15
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多