堆栈只显示第一个值?

时间:2013-11-26 22:36:20

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

我正在尝试使用动态分配的链表制作堆栈程序,而我对整个事情感到非常困惑。无论如何,我创建了自己的堆栈构造,但它只显示第一个元素。这是我的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;
};

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

1 个答案:

答案 0 :(得分: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;
}