-1

I want my program to remove nodes and return item in RemoveHead() function. I am not sure what is the mistake. In main() function , Everything is going fine but my program is not removing Headand its still printing the previous list L1: a non empty list.

To make it more clear i am uploading my output and desired output.

This is My program:

int main()
{
    cout << "===== Testing Step-1 =====\n";
    cout << "Testing default constructor...\n";
    LinkedList L1;
    L1.Print(); // should be empty
    cout<<"\nTesting AddHead()...\n";
    for(int i=0; i<10; i++){
        cout << i << ' ';
        L1.AddHead(i);
    }
    cout << endl;
    L1.Print();
    cout << "\nTesting IsEmpty() and RemoveHead()...\n";
    while(!L1.IsEmpty())
        cout << L1.RemoveHead()<< ' '; // should be printed in reverse
    cout << endl; 
    L1.Print(); // should be empty
}

int LinkedList::RemoveHead()
{
    if(Head==NULL)
    {
        cerr << "Error Occured. " << endl;
        exit(1);
    }
    else
    {       
        NodePtr temp;
        temp->Item = Head->Item;
        temp = Head;
        Head = Head->Next;
        delete temp;
    }
 //return 0; to be removed while compilation

bool LinkedList::IsEmpty()
{
  Head==NULL;
  return true;
}
void LinkedList::Print()
{

    if (Head==0)
    {
        cout << "Empty error ." ;
    }
    else
    {
        NodePtr crnt;
        crnt = Head;
        while(crnt!= NULL)
        {
            cout << crnt->Item << " ";
            crnt = crnt->Next;
        }
        cout << endl;
    }
}   

This is the output: enter image description here

My output should be something like:

===== Testing Step-1 =====
Testing default constructor...
List is empty.

Testing AddHead()...
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0

Testing IsEmpty() and RemoveHead()...
9 8 7 6 5 4 3 2 1 0
List is empty.
muzzi
  • 382
  • 3
  • 10
  • 1
    Please provide a minimum example code. Currently there is a lot of junk lines that discourage. – 273K Apr 25 '18 at 02:27
  • 1
    In `IsEmpty()`, `Head==NULL;` You forgot the `if`. Just make it `return Head == NULL;` – 001 Apr 25 '18 at 02:27
  • Also, `RemoveHead()` is incomplete. – 001 Apr 25 '18 at 02:30
  • Whats wrong with RemoveHead() ?? – muzzi Apr 25 '18 at 02:56
  • 1
    @muzzi 1. It's missing a closing `}` and 2. it does not return a value. – 001 Apr 25 '18 at 03:45
  • Possible duplicate of [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) – Raedwald Apr 25 '18 at 06:45

1 Answers1

1

As mentioned in a comment by Johnny Mopp :

Your IsEmpty() method should refactored from this:

bool LinkedList::IsEmpty()
{
  Head==NULL;
  return true;
}

To this:

bool LinkedList::IsEmpty()
{
  return Head==nullptr;
}

Thanks to codekaizer for pointing out using nullptr instead of NULL.

Rann Lifshitz
  • 4,040
  • 4
  • 22
  • 42