Saturday, 17 September 2016

Singly Linked List: Ordered list

Singly Linked List: Ordered 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_order(NODE first)
{
                int item;
                NODE temp, cur, prev;
                temp = getnode();

                printf("\nEnter the value: ");
                scanf("%d", &item);
                temp->data = item;

                if(first==NULL)
                                return temp;
                if(item < first->data)
                {
                                temp->link = first;
                                return temp;
                }
                prev = NULL;
                cur = first;
                while(cur!=NULL && item >= cur->data)
                {
                                prev = cur;
                                cur = cur->link;
                }

                prev->link = temp;
                temp->link = cur;
                return first;
}


void display(NODE first)
{
                NODE cur;
                cur = first;
                printf("\nContents are:");
                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_order(first);
                display(first);
}
Output:
Enter number of nodes for list: 6

Enter the value: 12
Enter the value: 34
Enter the value: 11
Enter the value: 90
Enter the value: 12
Enter the value: 44

Contents are:

| 11 | 7870320 | --> | 12 | 7877680 | --> | 12 | 7870216 | --> | 34 | 7877696 | --> | 44 | 7877664 | --> | 90 | 0 |



Also Check,