Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Why is this printing an infinite loop? #pragma once #include #include template class LinkedList { public: LinkedList(); ~LinkedList(); int getLength(); void print(); void add(Type); void
Why is this printing an infinite loop?
#pragma once
#include
#include
template
class LinkedList
{
public:
LinkedList();
~LinkedList();
int getLength();
void print();
void add(Type);
void remove(Type);
int length;
struct Node
{
Type val;
Node* next;
};
Node* head, *tail;
};
/**
* Sets head and tail to null, sets length to be empty.
*/
template
LinkedList::LinkedList()
{
head = tail = NULL;
length = 0;
}
/**
* Destructor for the Linked List.
*/
template
LinkedList::~LinkedList()
{
Node* prev = NULL;
Node* it = head;
while (it != NULL)
{
prev = it;
it = it->next;
delete prev;
}
}
/**
* Prints the whole linked list.
*/
template
void LinkedList::print()
{
int index = 0;
Node* it = head;
while (it != NULL)
{
std::cout << "{" << index << ":" << it->val << "}";
if (it->next != NULL)
{
std::cout << ", ";
}
it = it->next;
}
}
/**
* @return the number of nodes in the linked list.
*/
template
int LinkedList::getLength()
{
return length;
}
template
void LinkedList::add(Type value)
{
Node* newNode = new Node;
newNode->val = value;
newNode->next = NULL;
if (head == NULL)
{
head = tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
length++;
}
/**
* Removes all nodes that have the value passed in.
* @param value The value you want to remove.
*/
template
void LinkedList::remove(Type value)
{
Node* it = head;
Node* prev = NULL;
while (it->next != NULL)
{
if (it->val == value)
{
if (prev == NULL)
{
head = it->next;
delete it;
}
else
{
prev->next = it->next;
delete it;
}
}
prev = it;
it = it->next;
}
length--;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started