Я пытался связать список. После создания списка он пытается отобразить в прямом порядке, но он отображается в обратном порядке. Я предполагаю, что добавляю узлы в прямом положении, но почему он отображает последнее значение?ссылки отображаются в обратном порядке
Вот код
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
void add(num);
void insert();
void display();
struct node
{
int val;
struct node *next;
};
struct node *head =NULL;
main()
{
int data,i=0;
head = (struct node *)malloc(sizeof(struct node));
while(1)
{
printf("enter your choice");
scanf("%d",&i);
switch(i)
{
case 1:
insert();
break;
case 2:
display();
break;
default:
printf("thankyou");
}
}
}
void add(num)
{
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->val=num;
if (head== NULL)
{
head=temp;
head->next=NULL;
}
else
{
head->next = temp
head=temp;
}
}
void insert()
{
int ch;
if (head->val == NULL)
{
printf("Enter the value for the first node :");
scanf("%d",&ch);
add(ch);
}
else if(head->val != NULL)
{
printf("Enter the value to insert :");
scanf("%d",&ch);
add(ch);
}
}
void display()
{
struct node *newnode;
newnode = head;
if(newnode == NULL)
printf("invalid list");
else
{
while(newnode!=NULL)
{
printf("%d \t\t",newnode->val);
newnode=newnode->next;
}
}
}