Paula
Paula

Reputation: 13

How to delete element from list in c++

I am currently making a singly linked list in C++ Now I'm trying to make a function showList that prints the content of the list and if it is empty, prints "Empty list". However, right now it prints the list and "Empty list" every single time. When the list is empty, it prints an empty line and in new line "Empty list" Here is my current code:

template <typename T>
struct Node {
    T data;
    Node* next;
};

template <typename T>
void showList(const Node<T>* head){
    
    while (head != nullptr){
        std::cout << head->data << " " ;
        head = head->next;
    }
    std::cout << std::endl;

    if(head->data = 0){
       std::cout << "Empty list"<< std::endl;
    }

}

Upvotes: 1

Views: 85

Answers (1)

Mureinik
Mureinik

Reputation: 311073

Assuming you mean an empty list is a list where head is nullptr, you could check it explicitly:

void showList(const Node<T>* head) {
    if (head == nullptr) {
       std::cout << "Empty list"<< std::endl;
       return;
    }
    
    while (head != nullptr){
        std::cout << head->data << " " ;
        head = head->next;
    }
    std::cout << std::endl;
}

Upvotes: 2

Related Questions