SoloMael
SoloMael

Reputation: 53

Stack will only display first value?

I'm trying to make a stack program with a dynamically allocated linked list, and I'm very confused by the whole thing. Anyway, I made my own stack construct, but it only displays the first element. Here's my main.cpp file:

// (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;
}

Here are the functions used in the file:

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

Lastly, here are the structures that I used:

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

Can someone explain to me why there is only one value displayed? Please make it simple, I'm new to programming. Thanks!

Upvotes: 0

Views: 82

Answers (1)

sqykly
sqykly

Reputation: 1586

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

Upvotes: 1

Related Questions