Linked List output never ending loop

My extremely basic program to help me understand linked lists is driving me up the wall. It accepts the input perfectly, but when I try to step through the list to output the list to the screen, the WHILE loop goes bonkers.

Is there something I'm missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>

using namespace std;

struct newNode{
    int info;
    newNode* next;
};

int main()
{
    newNode* head;
    newNode* temp;
    newNode* nextNode;
    newNode* current;

    int number;
    int size=0;

    while (true){
        cout<<"Enter a number (negative number to end): ";
        cin>>number;

        if (number<0){
            break;
        }

        else{
            nextNode = new newNode;
            nextNode->info = number;

            if (size==0){
                head = nextNode;
                temp = nextNode;
            }

            temp->next = nextNode;
            temp = nextNode;

            //check that input goes where it's meant to
            cout <<nextNode->info <<endl;
            cout <<temp->info <<endl;
            cout <<head->info <<endl;
        }

        size++;
    }

    //Just so that I can find where the output is suppose to start
    cout <<"Input ended" <<endl <<endl;

    current = head;
    while (current != NULL) {
        cout<< current->info <<endl;
        current = current->next;
    }

    return 0;
}


and I've even had the output section as below before adding another pointer as per above:

1
2
3
4
5
6
    nextNode = head;
    while (nextNode != NULL) {
        cout<< nextNode->info <<endl;
        nextNode = nextNode->next;
    }
Last edited on
You never set the next pointer of the last node to NULL. Change lines 30-38 to
1
2
3
4
5
6
7
8
9
            nextNode->info = number;
            nextNode->next = NULL;
            if (size == 0) {
                head = nextNode;
                temp = nextNode;
            } else {
                temp->next = nextNode;
                temp = nextNode;
            }

Thank you so much!

I thought it had something to do with initializing the last node to NULL, but I had no idea where to do it.
Topic archived. No new replies allowed.