Reverse a linked list code with output


Code

#include<stdio.h>
#include<stdlib.h>

typedef struct node
{
        int id;
        struct node* next;            //for storing address of next node
}node;

node* create();
node* reverse(node*);
void display(node*);

node* create()
{
    node* head = NULL,*prev,*curr;

    do
    {
        if(head == NULL)
        {
            head = (node*)malloc(sizeof(node));
            printf("\n Enter eid ");
            scanf("%d",&head->id);
            head->next = NULL;
            prev = head;
        }

        else
        {
            curr = (node*)malloc(sizeof(node));
            printf("\n Enter eid ");
            scanf("%d",&curr->id);
            curr->next = NULL;
            prev->next = curr;
            prev = curr;
        }

        printf("\n Add more nodes? ");
        fflush(stdin);

    }while(getchar() == 'y');

    return head;
}


node* reverse(node* head)
{
    node *prev = NULL,*curr = head,*next = curr->next;

    while(curr!=NULL)
    {
        curr->next = prev;
        prev = curr;
        curr = next;
        next = curr->next;
    }
    return prev;
}

void display(node* head)
{
    node* curr=head;

    if(curr==NULL)
         printf("\n List is empty");
    else
    {
         printf("\n ");

         while(curr!=NULL)
         {
              printf("%d---",curr->id);
              curr=curr->next;
         }
    }
}


int main()
{
    node *head = NULL;
    int ch;

    do
    {
        printf("\n 1.Create linked list\n 2.Reverse\n 3.Display\n Enter choice ");
        scanf("%d",&ch);

        switch(ch)
        {
            case 1: 
                   head = create();
                   break;

            case 2:
                   head = reverse(head);
                   break;

            case 3:
                   display(head);
                   break;       
        }

        printf("\n Continue? ");
        fflush(stdin);

    }while(getchar()=='y');

    return 0;
}


O/P

Reverse-linked-list-output

No comments:

Post a Comment