Implement the removeAtPosition function of the LinkedList class . bool LinkedLis
ID: 3861892 • Letter: I
Question
Implement the removeAtPosition function of the LinkedList class .
bool LinkedList::removeAtPosition(int position)
The job of this function is to remove the node at the given position.
If given a position in legal range, the function will remove the node at that position, reduce the length by 1 and return true . For example, if the list is initially { 1, 2, 3 } and we call removeAtPosition(2) then the list will be changed to { 1, 3 }, length will be decreased from 3 to 2 and true will be returned.
If position is less than 1 or greater than length then the function should leave the list unchanged and return false .
Note that removing a node at position 1 requires that the headPtr be updated. In that case you may want to just call removeFirst to do the work for you.
Explanation / Answer
bool LinkedList::removeAtPosition(int position) {
// If linked list is empty
if (*head == NULL) return true;
// If position is less than 1
if (position < 1) return false;
// Store the head node
struct node* temp = *head;
// If head needs to be removed
if (position == 1){
removeFirst();
return true;
}
// Find the previous node of the node to be deleted
for (int i=1; temp!=NULL && i<position; i++) {
temp = temp->next;
}
// If position is greater than the length
if (temp == NULL || temp->next == NULL) {
return false;
}
// Node temp->next is the node to be deleted
// Store pointer to the next of node to be deleted
struct node *next = temp->next->next;
// Unlink the node from linked list
free(temp->next); // Free memory
temp->next = next; // Unlink the deleted node from list
return true;
}