Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my linked list only printing one value?

I created a linked list but it’s only printing the first value "1" and not the rest. I have an insert function to insert new nodes and then a show function to print out the node values but it’s only printing the first value.

struct Node {
    int n;
    Node *next;

};

class LinkedList {
    private:
        Node *head;
        Node *tail;
    
    public:
        LinkedList() {
            head = NULL;
            tail = NULL;
        }
        ~LinkedList(){};

        void insert_node(int value) {
            Node *new_node = new Node();
            new_node->n = value;
            new_node->next = NULL;

            if (head == NULL) {
                head = new_node;
                tail = new_node;
            }
            else {
                tail = new_node;
                tail->next = new_node;
            }
        }

        void show() {
            Node *new_node;
            new_node = head;

            while (new_node != NULL) {
                cout << new_node->n << endl;
                new_node = new_node->next;
            }
        }

};

int main() {

    LinkedList L;

    L.insert_node(1);
    L.insert_node(2);
    L.insert_node(4);
    L.insert_node(8);
    L.show();

}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The lines

                tail = new_node;
                tail->next = new_node;

means

                new_node->next = new_node;
                tail = new_node;

Therefore, no link from head to new_node is created.

The lines should be:

                tail->next = new_node;
                tail = new_node;

to first create link to the new node, and then update the tail pointer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading