Tuesday 13 January 2015

Program to Reverse a Linked list


#include<stdio.h>
#include<malloc.h>
struct node
{
    int value;
    struct node *link;
}
*start;
main()
{
  void createlist(int data);

void display();
void reverse();

int choice,m,i,n;
start=NULL;
while(1)
{ printf("\n------------MENU-------------\n");
printf("\n1.Create list");
printf("\n2.Disply information");
printf("\n3.Reverse");
printf("\n4.Exit");
printf("\n---------------------------\n");
printf("\nEnter your choice  :");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter the number of nodes to be entered :");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("Enter the element :");
scanf("%d",&m);
createlist(m);
        }
break;

case 2:
display();
break;
case 3:
reverse();
break;

case 4:
exit(0);

  default:
printf("Wrong choice");


}
}
}
void createlist(int data)
{
    struct node *temp;
    temp=(struct node *)malloc(sizeof(struct node));
    temp->value=data;
    temp->link=NULL;
    if(start==NULL)
    {
        start=temp;
    }
    else
    {
        struct node *q;
        q=start;
        while(q->link!=NULL)
        q=q->link;
        q->link=temp;
    }

}
void display()
{
    struct node *q;
if(start==NULL)
  printf("list is empty\n");
  else
{       q=start;
  printf("\n\nCurrent list is \n");
  while(q!=NULL)
{
printf("%d-->",q->value);
q=q->link;
}
}
}
void reverse()
{
    struct node *p,*q,*r,*temp;
    if(start==NULL)
    {
        printf("List is empty...\n");
        return;

    }
    p=start;
    q=start->link;
    p->link=NULL;
    while(q!=NULL)
    {
        r=q->link;
        q->link=p;
        p=q;
        q=r;
    }
    start=p;
    printf("List reversed successfully\n");
}
//output

------------MENU-------------

1.Create list
2.Disply information
3.Reverse
4.Exit
---------------------------

Enter your choice  :1

Enter the number of nodes to be entered :5
Enter the element :1
Enter the element :2
Enter the element :3
Enter the element :4
Enter the element :5

------------MENU-------------

1.Create list
2.Disply information
3.Reverse
4.Exit
---------------------------

Enter your choice  :2


Current list is
1-->2-->3-->4-->5-->
------------MENU-------------

1.Create list
2.Disply information
3.Reverse
4.Exit
---------------------------

Enter your choice  :3
List reversed successfully

------------MENU-------------

1.Create list
2.Disply information
3.Reverse
4.Exit
---------------------------

Enter your choice  :2


Current list is
5-->4-->3-->2-->1-->
------------MENU-------------

1.Create list
2.Disply information
3.Reverse
4.Exit
---------------------------

Enter your choice  :4

Process returned 0 (0x0)   execution time : 35.026 s
Press any key to continue.

No comments:

Post a Comment