I am trying to reverse a linked list in c, that I created by copying the data from a structure.
I have created the following function named reverselist, after reading a lot of suggestions about reversing a list, but after applying it, and trying again to print I get nothing printed on my screen.
I don't want to just print the file, but I want the linked list permanently changed. Can someone spot out what is the problem in my code?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int i,j,temp;
typedef struct{
int nr;
}PASSENGERS;
typedef struct list1{
int nr;
struct list1 *next;
}LIST1;
LIST1* reverselist (LIST1 *head)
{
LIST1 *cursor=NULL;
LIST1 *next;
while(head){
next=head->next;
head->next=cursor;
cursor=head;
head=next;
}
return cursor;
}
int main()
{
PASSENGERS passenger[53];
for (j=0;j<53;j++)
passenger[j].nr=j+1;
PASSENGERS *start=NULL;
char selection;
do{
printf("0. Exit and Print File\n");
scanf(" %c",&selection);
} while (selection!='0');
LIST1 *list1, *start=NULL;
for (i=0;i<53;i++){
list1 = (LIST1 *) malloc (sizeof(LIST1));
list1->next = NULL;
list1->nr = passenger[i].nr;
if (start ==NULL)
start = list1;
else //add new node at the beginning of list
{
list1->next = start;
start = list1;
}
}
LIST1 *current = list1;
printf("The original list is:");
while (current !=NULL) /* Printing the names on the list ok*/
{
printf("%d\n",current->nr);
current = current->next;
}
LIST1* head = NULL;
head=reverselist(head);
printf("The reversed list is:");
while (current !=NULL){
printf("%d\n",current->nr);
current = current->next;
}
}