I am trying to insert a node at a specific position. In my code, numbers with position 1 are only inserted (mainly at the beginning of the linked list), and it does not insert any data with position 2. Is there something wrong with temp2? When I ran the program, it did not indicate everything that I think.
I know how you guys hate the homework asked here, but I just don't know what is wrong with my program. I'm just new to this, and my teacher did not explain the linked list very well.
The code is below.
- The result that I get is 8 7
-I would like him to read 8 6 7 5, where 6 and 5 are inserted in position 2
#include<stdlib.h>
#include<stdio.h>
struct Node
{
int data;
struct Node* next;
};
struct Node *head;
void Insert(int data, int n)
{
Node* temp1 = new Node();
temp1->data = data;
temp1->next = NULL;
if (n == 1){
temp1->next = head;
head = temp1;
return;
}
Node* temp2 = new Node();
for (int i = 0; i < n-2; i++){
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp2;
}
void print()
{
Node* temp = head;
while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
printf("\n");
}
int main()
{
head = NULL;
Insert(7,1);
Insert(5,2);
Insert(8,1);
Insert(6,2);
print();
system("pause");
}