Reverse Single Linked List – C Program Source Code


The below program performs the following:

  1. Takes input of the size of the Linked List as Command Line argument.
  2. Creates a Singly Linked List of input size (default: 20 members) filled with random numbers.
  3. Prints the members of the Linked List.
  4. Reverses the Linked List and prints it again.

Source Code:

#include<stdio.h>
#define NELEMENTS 20
struct node
{
 int value;
 struct node *next;
};
struct node* CreateLinkedList(int, struct node*);
void printList(struct node*);
struct node* Reverse(struct node*);
int main(int argc, char *argv[])
{
 struct node *head;
 int NofElements;
 if(argc == 2)
 NofElements = atoi(argv[1]);
 else
 NofElements = NELEMENTS;
 head = CreateLinkedList(NofElements, head);
 printList(head);
 head = Reverse(head);
 printList(head);

 char c;
 c = getchar();
 return(0);
}
struct node* CreateLinkedList(int NElements, struct node *head)
{ 
 struct node *temp = NULL;
 temp = (struct node*) malloc(sizeof(struct node));
 head = temp;

 for( ; NElements>0; NElements--, temp=temp->next)
 {
 temp->value = rand();
 temp->next = (struct node*) malloc(sizeof(struct node));

 }
 temp->value = '';
 temp->next = NULL;

 return(head);
}
void printList(struct node *head)
{
 struct node *temp;

 for(temp=head; (temp->value)!=''; temp=temp->next)
 printf("%8d", temp->value);
printf("\n");
}
struct node* Reverse(struct node *head)
{
 struct node *temp_prev, *temp, *temp_post;

 for(temp_prev=head,temp=head->next; (temp_prev->next)!=NULL && (temp->next)!= NULL; )
 {
 temp_post = temp->next;
 temp->next = temp_prev;
 temp_prev = temp;
 temp = temp_post;
 }
 head->next = temp;
 head = temp_prev;

 return(head);
}

Leave a comment