Answer to Question #239039 in C++ for Olivia

Question #239039
Write a C++ program that tells the size of linked list and counts the elements present in the list and displays the data

Note:
no global declarations
Make class or struct
1
Expert's answer
2021-09-20T02:59:40-0400
#include <iostream>
using namespace std;
class Node{
    public:
    int data;
    Node *next, *prev;
    Node();
    Node(int);
};
Node::Node(){
    next = NULL;
    prev = NULL;
}
Node::Node(int data){
    this->data = data;
    next = NULL;
    prev = NULL;
}
class LinkedList{
    static Node *head, *tail;
    int size;


    public:
    LinkedList();
    void append(int);
    int len();
    void show();
};
Node* LinkedList::head = NULL;
Node* LinkedList::tail = NULL;
LinkedList::LinkedList(){
    size = 0;
}
void LinkedList::append(int data){
    if(head == NULL){
        head = new Node(data);
        tail = head;
        size++;
    }
    else{
        tail->next = new Node(data);
        tail = tail->next;
        size++;
    }
}
int LinkedList::len(){
    return size;
}
void LinkedList::show(){
    Node* curr = head;
    while(curr != NULL){
        cout<<curr->data<<" ";
        curr = curr->next;
    }
    cout<<endl;
}
int main(){
    LinkedList list;
    cout<<"There are currently "<<list.len()<<" elements in the list\n";
    cout<<"Adding 1, 2 and 3...";
    list.append(1);
    list.append(2);
    list.append(3);
    cout<<"There are currently "<<list.len()<<" elements in the list\n";
    cout<<"\nThe items in the list are\n";
    list.show();


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS