简体   繁体   中英

Implementing a linked list in c++

This code is printing 30 only what's wrong on this?

I've followed this tutorial https://www.codementor.io/codementorteam/a-comprehensive-guide-to-implementation-of-singly-linked-list-using-c_plus_plus-ondlm5azr

I've no idea on how this printing only 30? Anything wrong on this code?

#include <iostream>

using namespace std;

struct node {
    int data;
    node *next;
};

class LinkedList {
    private:
        node *head, *tail;

    public:
        LinkedList() {
            head = NULL;
            tail = NULL;
        }

        // For adding nodes
        void addNode(int value) {
            node *tmp = new node;
            tmp->data = value;
            tmp->next = NULL;

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

        // For displaying nodes
        void display() {
            node *tmp = head;

            while(tmp != NULL) {
                cout << tmp->data << endl;
                tmp = tmp->next;
            }
        }
};

int main()
{
    LinkedList a;

    // For adding nodes
    a.addNode(10);
    a.addNode(20);
    a.addNode(30);

    // For displaying nodes
    a.display();

    return 0;
}

if condtion always returns true:

if(head == tail) {

at first insertion it returns true because head and tail are NULLs. At the second insertion this condition returns true as well, because head and tail are the same, and so on. So you don't add new items, but you always overwrite the first item.

You should fix it by

 if (head == NULL)

我认为错误在 if(head == tail) 行,如果将其更改为 if(head == NULL) 它应该打印 10 20 30。但是,如果您想知道为什么 if(head == tail) 导致这个问题是因为对于每个 addNode 操作,head 和 tail 都是相等的,最后 head 也指向 30!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM