Finish implementing the List class (in list.h): Implement a following member fun
ID: 3737422 • Letter: F
Question
Finish implementing the List class (in list.h):
Implement a following member functions:
• removeAt : Remove the node at the specified index. Return the int value contained at the now removed node. Exit program if an invalid index is provided.
• remove : Remove the provided value if it is contained in the list. Return true if the value was found and remove, return false if no changes were made to the list.
• at : Returns the int value contained at the node at the provided index. Exit program if an invalid index is provided.
• valueOf : Given a ListNode pointer, return the given value
• getNext : Given a ListNode pointer, return a pointer to its next ListNode
• getPrevious : Given a ListNode pointer, return a pointer to its previous ListNode
In the list.h file, do not modify any of the contents of the List class unless they are marked with a TODO comment.
List.h:
Explanation / Answer
int List::removeAt(int index){
if (index < 0 || head == NULL)
exit(0);
int count = 0;
ListNode *curr = head;
if (index == 0){
int a = head->data;
head = head->next;
delete curr;
return a;
}
ListNode *q = curr;
while (curr != NULL && count != index){
q = curr;
curr = curr->next;
count++;
}
if (count == index){
int a = curr->data;
q->next = curr->next;
delete curr;
return a;
}
else {
exit(0);
}
}
bool List::remove(int value){
ListNode *p = head;
if (p == NULL){
return false;
}
if (p->data == value){
head = head->next;
delet p;
return true;
}
ListNode *q;
q = p;
while (p!= NULL && p->data != value){
q = p;
p = p->next;
}
if (p == NULL){
return false;
}
else {
q->next = p->next;
delete p;
return true;
}
}
int List::at(int index){
ListNode *curr = head;
if (index < 0 || head == NULL)
exit(0);
int count = 0;
ListNode *p = head;
if (index == 0){
return head->data;
}
while (curr != NULL && count != index){
curr = curr->next;
count++;
}
if (count == index){
return curr->data;
}
else {
exit(0);
}
}
int List::valueOf(const ListNode *node){
return node->data;
}
const ListNode *getNext(const ListNode *node){
return node->next;
}
const ListNode *getPrevious(const ListNode *node){
return node->previous;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.