well im starting with C and i've been asked to do a linked list that has random integers in its nodes data, they must be in ascendant order and later i have to reverse their order with a function. The problem im having is that in my reverse output, im only getting the first number and its not even reversed.
#include <stdio.h>
#include <stdlib.h>
int N;
typedef struct node{
int num;
struct node *next;
}nodes;
int first_node(nodes *head){
if(head == NULL){
printf("Error");
}
else{
head -> num= rand();
head->next=NULL;
}
}
int second_node(nodes *head){
nodes *uno=malloc(sizeof(nodes));
if(uno == NULL){
printf("Error");
}
else{
uno->num = rand();
uno->next = NULL;
if( uno->num>head->num){
head->next=uno;
}
else{
head= uno->next;
}
}
}
int insert_node(nodes *head){
nodes *dos=malloc(sizeof(nodes));
if(dos == NULL){
printf("Error");
}
else{
dos->num = rand();
dos->next = NULL;
nodes *current = head;
while(current!= NULL){
if(current->num<dos->num && current->next==NULL){
current->next = dos;
return;
}
else if (current->num<dos->num && current->next->num>dos->num){
dos->next=current->next;
current->next=dos;
return;
}
else if(head->num>dos->num){
dos->next=head;
head=dos;
}
current=current->next;
}
}}
void printnodes(nodes *head){
nodes *current = head;
while (current != NULL){
printf("%d\n",current->num);
current = current ->next;
}
}
void reverse(nodes *head)
{
nodes *a=head->next;
if(a!=NULL)
{
nodes *b=a->next;
a->next=head;
head->next=NULL;
head=a;
if(b!=NULL)
{
while(b!=NULL)
{
a=b;
b=b->next;
a->next=head;
head=a;
}
a->next=head;
head=a;
}
}
}
int main(){
printf("Insert the number of nodes u want to create:");
scanf("%d", &N );
nodes *head =malloc(sizeof(nodes));
int i =3;
if(N==1){
first_node(head);
}
else if (N ==2){
first_node(head);
second_node(head);
}
else if (N>2){
first_node(head);
second_node(head);
while(i<=N){
insert_node(head);
i++;
}
}
printnodes(head);
printf("\n\n Reversed \n\n");
reverse(head);
printnodes(head);
return 0;
}
The output im getting creating 5 nodes is : In order: 41 3445 3890 8709 16777
Reversed : 41
how can i fix this?, thanks and sorry for the bad english