Which condition checks the emptiness of the linked list?

With a root

The root acts as an element which is always present even if the list is empty.
The other use of having a root in list is that we can link the last element back to the root forming a cycle. According to this concept, next of any node is never NULL.

Show

Pseudocode:

bool isEmpty(node *root){ if (root->next == root) return true; else return false; }

The implementation is given below:

#include<bits/stdc++.h> using namespace std; class Node{ public: int data; Node *next; Node(){ data=0; next=NULL; } }; class linked_list{ Node *root; public: linked_list(){ root=NULL; } Node* getRoot(){ return root; } void add_node(int n){ Node *temp = new Node(); temp->data = n; temp->next = NULL; if(root == NULL){ root=temp; root->next=root; } else{ Node *last=root; while(last->next!=root){ last=last->next; } temp->next=root; last->next=temp; } } void printList(){ Node *temp=root; if(temp!=NULL){ do{ cout<<temp->data<<" "; temp = temp->next; } while(temp!=root); } } bool isEmpty(){ if(root->next==root && root->data==0) return true; return false; } }; int main(){ linked_list l1; l1.add_node(5); l1.add_node(10); l1.add_node(15); if(l1.isEmpty()) cout<<"The list is empty!\n"; else { cout<<"The list is not empty! List contains:\n"; l1.printList(); } return 0; }

Output:

1. if not seq:

In Python, empty lists evaluate False, and non-empty lists evaluate True in boolean contexts. Therefore, you can simply treat the list as a predicate returning a Boolean value. This solution is highly Pythonic and recommended by the PEP8 style guide.

1
2
3
4
5
6
7
if __name__ == '__main__':
a = []
if not a:
print("List is empty")

DownloadRun Code