void LinkedList::insert(int num, int pos) {
Node *newNode = new Node;
newNode->data = num;
newNode->next = NULL;
if(pos == 0) {
newNode->next = head;
head = newNode;
}
else {
Node *temp = head;
for (int i = 1; i < pos-1; ++i) {
if (temp != NULL) {
temp = temp->next;
}
}
if (temp != NULL) {
newNode->next = temp->next;
temp->next = newNode;
}
else {
cout << " The previous node is full.";
}
}
}
This is my insert function. The code that runs in main.cpp is:
// adding through insert
nums.insert(1, 0);
nums.insert(5, 4);
nums.insert(3, 7);
And the output is:
List after append:
8 6 7 8 0 9
List after inserting:
1 8 6 5 7 8
As you can see, something is getting overwritten, or the end of the list just gets cut off. I have searched the internet for hours to no avail. The output needs to increase the length of the list and not overwrite anything. Any help would be appreciated.