Program to reverse the elements of a single linked list

Program to reverse the elements of a single linked list in C

#include<stdio.h>
struct node
 {
  int data;
  struct node *next;
 } *head,*temp,*temp1,*first,*last;
void create();
void swap(struct node*,struct node*);
void reverse();
void print();

void main()
 {
   create();
   printf("\nElements in the entered list:\n");
   print();
   reverse();
   printf("\nElements after reversing the entered list:\n");
   print();
 }

void create()
 {
   int num;
   printf("\nEnter element or enter -1 to exit\n");
   head=(struct node*)malloc(sizeof(struct node));
   scanf("%d",&num);
   if(num==-1)
     {
      head=NULL;
     }
   else
     {
       head->data=num;
       head->next=NULL;
     }
   while(head!=NULL)
     {
       printf("\nEnter element or enter -1 to exit\n");
       scanf("%d",&num);
       if(num==-1)
{break;}
       else
{
 temp=head;
 while(temp->next!=NULL)
   {
     temp=temp->next;
   }
 temp1=(struct node*)malloc(sizeof(struct node));
 temp1->data=num;
 temp1->next=NULL;
 temp->next=temp1;
}
     }
 }
/* Reverse function is for reversing the linked list.It swaps the first and last element,first+1 and last-1 and so on.until it reaches the middle of linked list. */
void reverse()
 {
  first=head;
  last=head;
  while(last->next!=NULL)
   {
    last=last->next;
   }
  while(first!=last&&last->next!=first)
   {
    swap(first,last);
    for(temp=first;temp->next!=last;temp=temp->next);
    last=temp;
    first=first->next;
   }
 }
void print()
 {
   struct node *head1=head;
   while(head1!=NULL)
    {
     printf("%d\t",head1->data);
     head1=head1->next;
    }
 }
/*Swap functions takes first and last node's pointers and swaps the elements in that nodes*/
void swap(struct node *p,struct node *q)
 {
  int k;
  k=p->data;
  p->data=q->data;
  q->data=k;
 }

Output of the above Program: frenzz try with different inputs.........

REVERSING-SINGLE-LINKED-LIST

Share on Google Plus
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment