Saturday, 17 September 2016

Singly Linked List: Reverse the List

Singly Linked List: Reverse the List



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

struct node
{
                int data;
                struct node *link;
};
typedef struct node * NODE;

NODE getnode()
{
                NODE x;
                x = (NODE)malloc(sizeof(struct node));
                if(x==NULL)
                {
                                printf("\nInsufficient memory");
                                exit(0);
                }
                x->link = NULL;
                return x;
}

NODE insert(NODE first)
{
                int val;
                NODE temp, cur;
                temp = getnode();
                printf("\nEnter the value: ");
                scanf("%d",&val);
                temp->data = val;

                if(first == NULL)
                                return temp;

                cur = first;
                while(cur->link!=NULL)
                {
                                cur = cur->link;
                }
                cur->link = temp;
                return first;
}

NODE reverse(NODE first)
{
                NODE rev, temp;
                if(first==NULL)
                {
                                printf("\nList empty")   ;
                                return NULL;
                }
                rev =NULL;
                while(first!=NULL)
                {
                                temp = first;
                                first= first->link;
                                temp->link = rev;
                                rev =temp;
                }
                return rev;
}

void display(NODE first)
{
                NODE cur;
                cur = first;
                printf("\nContents are:\n");
                if(cur == NULL)
                                printf("\nList is empty. Nothing to display.");
                else
                {
                                while(cur!=NULL)
                                {
                                                printf("| %d | %d | => ", cur->data, cur->link);
                                                cur = cur->link;
                                }
                }
}

void main()
{
                int ch,i, n;
                NODE first = NULL;

                printf("\nEnter number of nodes for list: ");
                scanf("%d", &n);
                for(i=0;i<n;i++)
                                first = insert(first);
               
                printf("\nBefore Reverse: \n");
                display(first);

                first = reverse(first);

                printf("\nAfter Reverse: \n");
                display(first);
}

Output:
Enter number of nodes for list: 4

Enter the value: 11
Enter the value: 12
Enter the value: 13
Enter the value: 14

Before Reverse:
Contents are:
| 11 | 7673608 | => | 12 | 7681016 | => | 13 | 7681032 | => | 14 | 0 |

After Reverse:
Contents are: