Creating a Linked List

closed account (oEwqX9L8)
I'm working on a project to create my own linked list and I'm having some trouble with the print function. Specifically, how to iterate through the pointers to items in the list. Each node has pointers to the previous and next items in the list. I also have a head and tail pointer.

This is my class declaration.
1
2
3
4
5
6
7
8
9
10
11
12
13
  template<typename ItemType>

class LinkedList {
public:
    struct Node {
        ItemType item;
        Node* next;
        Node* prev;
    };
    
    Node* head;
    Node* tail;
    int size = 0;


This is my idea for a loop to print the nodes.
1
2
3
4
5
6
7
8
9
10
11
 string printList() {
        stringstream ss;
        int nodeCounter = 0;
        ss << "print" << endl;
        for (Node* i = head; i != tail; i = i->next) {
            ss << "node " << nodeCounter << ": " << *i << endl;
            nodeCounter++;
        }
        
        return ss.str();
    }

But (obviously) it's not working. I think my problem is with, "i = i->next."
I want to start at the "head" pointer for the list and then jump to the "next" pointer for each node.

Any ideas or suggestions are very welcome, thanks for any help!
Last edited on
Maybe you can create a new pointer to Node and assign it the head. Then you do a while-loop that iterate as long as the next item doesn't point to NULL.

while (newPointer != NULL){
cout<< newPointer->item;
newPointer = newPointer->next;
}

EDIT: Had written something wrong on the while-line. Corrected now :)
Last edited on
closed account (oEwqX9L8)
Brilliant! Thanks for your help!
Topic archived. No new replies allowed.