I am creating a simple linklist of integers and then reversing it. While reversing, last integer in original list is not getting printed. Instead a garbage value is printed. Here is the code:
#include<stdio.h>
#include<stdlib.h>
struct list
{
int node;
struct list *next;
};
void insert(struct list **, int);
void print(struct list *);
int main()
{
struct list *mylist= NULL, *tmp = NULL;
insert(&mylist, 10);
tmp = mylist;
insert(&mylist, 20);
insert(&mylist, 30);
insert(&mylist, 40);
insert(&mylist, 50);
insert(&mylist, 60);
insert(&mylist, 70);
mylist=tmp;
reverse(&mylist);
printf("hello ");
print(mylist);
return 0;
}
void reverse(struct list **temp)
{
struct list **pre, **aft, **head;
*pre = NULL;
*head = *temp;
if(*head == NULL )
{
return;
}
else
{
while((*head)!= NULL)
{
*aft =(*head)->next;
(*head)->next = *pre;
*pre = *head;
*head = (*aft);
printf("%d\t",(*pre)->node);
}
*temp = *pre;
}
}
void print(struct list *head)
{
if(head==NULL)
return;
else
{
while(head!=NULL)
{
printf("%d\t",head->node);
head=head->next;
}
}
}
void insert(struct list **head, int value)
{
struct list *new_node;
new_node = (struct list *)malloc(sizeof(struct list));
//node Creation
new_node->node=value;
new_node->next=NULL;
//Adding Node to list
if(*head==NULL)
{
*head=new_node;
}
else
{
while((*head)->next!=NULL)
{
*head=(*head)->next;
}
(*head)->next=new_node;
}
}
Output: 10 20 30 40 50 60 6532425 hello 6532425 60 50 40 30 20 10
Why?