Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Stuck on this C++ Linked List question. I\'m trying to write the implementation

ID: 669017 • Letter: S

Question

Stuck on this C++ Linked List question. I'm trying to write the implementation for an Insert function. Here are the guidelines:

Inserts an element at index (so that once inserted it is at that index) into the linked list. This is one of the more tricky ones. You'll need to talk the list until you find the index you want to insert at (maybe one before that, hint hint) and 'wire' in the new element. Whiteboard this one out!!
_________

bool LinkedList::InsertAtIndex(int value, int index) {
std::cout << "Don't forget, you can use cout to debug things! The output "
"apears ABOVE the test output" << std::endl;
return true;
}

_______

So I need to fill in the body of the InsertAtIndex bool function. I'll include the header file below which has a struct and a class in it. Any help would be amazing!

struct LinkedListNode {
int data;
LinkedListNode* next_node;
};

class LinkedList {
public:
LinkedList();
int Size();
bool InsertAtIndex(int value, int index);
void PushFront(int value);
void PushBack(int value);
int& operator[] (int index);
bool RemoveAtIndex(int index);
void Clear();

void RemoveAll(int value);

LinkedListNode* head;
};

Explanation / Answer

bool LinkedList::InsertAtIndex(int value, int index) {
      if (index > size())
             return false; // error as index is greater that the size of Linked List

   LinkedListNode *p = head; //Traversing the list from start till index
   while (index) {
      p = p->next_node;
      --index;
   }

   LinkedListNode *z = new LinkedListNode; // Creating new node of Linked List
   z->data = value; // Providing value to the node
   z->next_node = p->next_node;
   p->next_node = z;

   return true;
}