So am making a linked list. printing it out. and reversing it. and then printing it out. first time I make it and print it out. everything works fine. but when I reverse it. it reverses successfully. but when I print it. I go out of bounds even though I use the same code I did first.
Here is the reverse function
void reverse_list(Node_ptr* head){
Node_ptr temp2;
Node_ptr temp3 = NULL;
temp2 = (Node_ptr)malloc(sizeof(Node));
temp3 = (Node_ptr)malloc(sizeof(Node));
if (temp2==NULL || temp3==NULL)
{
printf("Failed to allocate node\n");
exit(1);
}
while (*head!=NULL) {
temp2 = (*head)->next;
(*head)->next = temp3;
temp3 = (*head);
(*head) = temp2;
}
*head = temp3;
}
here is the print function
temp = head;
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
reverse_list(&head);
temp = head;
while (temp != NULL)
{
printf("%d\n", temp->data);
temp = temp->next;
}
for some reason it tries to print garbage after the last element