Click here to Skip to main content
15,902,276 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I was implemeting LinkedList in c++.

I was expecting :

List is not empty!!
4	


But result was :

List is not empty!!
5	


and Funny how that when I debug and so 'Step over' and over again, I got the expected result. Is there anyone who tells me that I'm missing something?



#include <iostream>
using namespace std;

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

class LinkedList {
    node *head;
    node *tail;
    
public:
    LinkedList(){
        head = nullptr;
        tail = nullptr;
    };
    
    void createNode(int value);
    void display();
};

void LinkedList::createNode(int value){
    node *temp = new node;
    temp->data = value;
    temp->next = nullptr;
    
    if(head == nullptr){
        head = temp;
        delete temp;
        temp = nullptr;
    } else {
        cout << "List is not empty!!" << endl;
    }
};

void LinkedList::display() {
    node *displayNode = new node;
    displayNode = head;
    while(displayNode != nullptr)
    {
        cout<<displayNode->data<<"\t";
        displayNode=displayNode->next;
    }
}

int main(){
    LinkedList *list1 = new LinkedList();
    list1->createNode(4);
    list1->createNode(5);
    
    list1->display();
};


What I have tried:

I have tried compile and debugging.
Posted
Updated 8-Jul-18 18:42pm

1 solution

You have not finished coding. Technically, if you have finished whatever you have done bug free, your output would have
List is not empty!!
4


Let's focus at your createNode function
void LinkedList::createNode(int value){
    node *temp = new node;
    temp->data = value;
    temp->next = nullptr;
    
    if(head == nullptr){
        head = temp;
        delete temp; // if you delete this head variable become invalid. remove this
        temp = nullptr;
    } else {
        // you have not implement what would happen if the list is not empty.
        cout << "List is not empty!!" << endl;
    }
};
 
Share this answer
 
Comments
CPallini 9-Jul-18 4:19am    
5.
Mohibur Rashid 9-Jul-18 5:00am    
thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900