Linked Lists in Classes - Program Not Working

Hey there I'm having trouble with coding linked lists as a class. This is my "Lists.h" file:
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
#include <string>
#include <iostream>

using namespace std;

#ifndef LISTS_H
#define LISTS_H


class List {
    public:
        struct node {
            int entryNum, keyNum;
            string keyword[4];
            string actWord[2];
            string storyLine;
            node* next;
        };

        node* head;

        List();
        node* addNode(int);
        node* getNode(int);
        void display();
};

#endif // LISTS_H 


And this is my "Lists.cpp" file:
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
#include "Lists.h"

List::List() {
    head = new node;
    head->entryNum = 0;
    head->next = 0;
}


List::node* List::addNode(int n) {
    node* newNode = new node;
    newNode->entryNum = n;
    newNode->next = 0;

    node *cur = head;
    while(cur) {
        if(cur->next == 0) {
            cur->next = newNode;
            return newNode;
        }
    }
}

List::node* List::getNode(int n) {
    node *cur = head;
    while(cur) {
        if(cur->entryNum == n) {
            cout << "Found Node " << cur->entryNum << " in list." << endl;
            return cur;
        }
        cur = cur->next;
    }
    cout << "No Node " << n << " in list.\n";
}

void List::display() {
    node *cur = head;
    while(cur) {
        cout << "Node " << cur->entryNum << endl;
        cur = cur->next;
    }
}


I can execute this in main:
1
2
3
List story;
story.addNode(1);
story.display();

But whenever I try to add more than 1 node to my program:
1
2
3
4
5
List story;
story.addNode(1);
story.display();
story.addNode(2);
story.display();

it just stops working. It doesn't freeze up, it just sits there perpetually with the cursor blinking. I'm not overly confident with the concept of nesting structures, and I'm lucky I actually got it to sort of work, but it would be appreciated if someone could tell me what I'm doing wrong.
1
2
    while(cur) {
        if(cur->next == 0) {
If first node -> next is not null pointer, it will go for another iteration of the loop and check first node again, and again, and again...

Also in your List::getNode you do not return anything if nothing was found. It will lead to stack corruption and obscure bugs. Return null pointer instead.
Thank you sooo much, kind sir!! Fixed my problem, plus, I was getting those warnings after compile, but I didn't know what to do about them. Now I know :) Thank you

EDIT: One last question, if you have the time: The reason I'm using nested structures is because I didn't want each node to have the node-related functions unnecessarily. Is that what this code will achieve?
Last edited on
Topic archived. No new replies allowed.