+92 332 4229 857 99ProjectIdeas@Gmail.com

How to check whether a singly linked list is empty or not (C++)


Checking whether linked list is empty or not ?
IsEmpty() returns 1 if the linked list is empty and returns 0 in case if the linked list is not empty.
Summary of IsEmpty()
Only a single line conditional statement is used to check whether the linked list is empty or not.
return head==NULL?true:false;
This statement checks if the head is equal to NULL, then it returns true and if the value of the head is not equal to NULL, then it returns false.

Code

#include "stdafx.h"
#include "iostream"
#include "conio.h"

using namespace std;

struct Node
{
public:
       int data;
       Node*link;
      
       Node();
};

Node::Node()
{
       data=0;
       link=NULL;
}

class LinkList
{
public:
       Node*head;
       LinkList();
       void AddNodeAtEnd(int);
       bool IsEmpty();
};

LinkList::LinkList()
{
       head=NULL;
}

void LinkList::AddNodeAtEnd(int _data)
{
       Node*node=new Node();
       node->data=_data;
       node->link=NULL;
      
       if(head==NULL)
              head=node;
       else
       {
              Node*tptr=head;
              while(tptr->link!=NULL)
                     tptr=tptr->link;
              tptr->link=node;
       }
}

bool LinkList::IsEmpty()
{
       return head==NULL?true:false;
}

int main()
{
       LinkList l;
      
       cout<<l.IsEmpty();cout<<endl;

       // Adding first  element to the linked list
       l.AddNodeAtEnd(10);
       // Adding second element to the linked list
       l.AddNodeAtEnd(20);
       // Adding third  element to the linked list
       l.AddNodeAtEnd(30);

       cout<<l.IsEmpty();cout<<endl;

       _getche();
       return 0;
}

Output
1
0

0 comments: