-2

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;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • 2
    You really should learn how to use your debugger. This will save you a lot of time in the future. – Jabberwocky Nov 08 '18 at 10:45
  • which compiler do you use?? – Bikash Gurung Nov 08 '18 at 10:48
  • There are no known good online C++ tutorials, and that one has both syntax errors and memory leaks. Check out [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Nov 08 '18 at 11:03
  • @molbdnilo yes bro c++ data structures and algorithms online tuts are hard to find. I studied DSA in javascript and I'm slowing converting the gained knowledge in c++ – Bikash Gurung Nov 08 '18 at 11:07

2 Answers2

2

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)
rafix07
  • 20,001
  • 3
  • 20
  • 33
0

I think the error is at line if(head == tail), if you change it to if(head == NULL) it should print 10 20 30. However, if you are wondering why if(head == tail) is causing this issue is because for every addNode operation head and tail are equal and at last head is also poiting to 30!