//Complete the C++ function to find the length of a linked list. #include <iostr
ID: 3729614 • Letter: #
Question
//Complete the C++ function to find the length of a linked list.
#include <iostream>
using namespace std;
class Node {
public:
Node *next;
int data;
Node(int d) {
data = d;
next = nullptr;
}
};
class LinkedList {
public:
Node *head;
Node *tail;
LinkedList() {
head = nullptr;
tail = nullptr;
}
void push(int data) {
Node *newNode = new Node(data);
if (!head) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
int getCount() {
// Complete this Function
}
void deleteList() {
Node *curr = head;
Node *next = nullptr;
while (curr) {
next = curr->next;
delete curr;
curr = next;
}
head = nullptr;
}
};
int main() {
LinkedList l1;
l1.push(8);
l1.push(9);
l1.push(3);
l1.push(14);
l1.push(5);
LinkedList l2;
l2.push(8);
l2.push(18);
LinkedList l3;
LinkedList l4;
l4.push(42);
LinkedList l5;
l5.push(8);
l5.push(1);
l5.push(12);
cout << l1.getCount() << endl;
cout << "Expected: 5" << endl;
cout << l2.getCount() << endl;
cout << "Expected: 2" << endl;
cout << l3.getCount() << endl;
cout << "Expected: 0" << endl;
cout << l4.getCount() << endl;
cout << "Expected: 1" << endl;
cout << l5.getCount() << endl;
cout << "Expected: 3" << endl;
l1.deleteList();
l2.deleteList();
l3.deleteList();
l4.deleteList();
l5.deleteList();
return 1;
}
Explanation / Answer
//Complete the C++ function to find the length of a linked list.
#include <iostream>
using namespace std;
class Node {
public:
Node *next;
int data;
Node(int d) {
data = d;
next = nullptr;
}
};
class LinkedList {
public:
Node *head;
Node *tail;
LinkedList() {
head = nullptr;
tail = nullptr;
}
void push(int data) {
Node *newNode = new Node(data);
if (!head) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
int getCount() {
Int count =0;
Node *currentNode = head;
while (currentNode != nullptr) {
count ++;
currentNode = currentNode -> next;
}
return count;
}
void deleteList() {
Node *curr = head;
Node *next = nullptr;
while (curr) {
next = curr->next;
delete curr;
curr = next;
}
head = nullptr;
}
};
int main() {
LinkedList l1;
l1.push(8);
l1.push(9);
l1.push(3);
l1.push(14);
l1.push(5);
LinkedList l2;
l2.push(8);
l2.push(18);
LinkedList l3;
LinkedList l4;
l4.push(42);
LinkedList l5;
l5.push(8);
l5.push(1);
l5.push(12);
cout << l1.getCount() << endl;
cout << "Expected: 5" << endl;
cout << l2.getCount() << endl;
cout << "Expected: 2" << endl;
cout << l3.getCount() << endl;
cout << "Expected: 0" << endl;
cout << l4.getCount() << endl;
cout << "Expected: 1" << endl;
cout << l5.getCount() << endl;
cout << "Expected: 3" << endl;
l1.deleteList();
l2.deleteList();
l3.deleteList();
l4.deleteList();
l5.deleteList();
return 1;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.