Saturday 3 January 2015

Creating a simple linked list in C language.

Linked list programming is the best method to learn memory optimization in C. While we use array we actually it is static bind of memory, and works like a multistoried apartment which consists of thousands of flat but only a few is used while rest of them are empty (unused). Same can be with simple pointers, where you allocate blocks dynamically but as you went on deleting values memory cannot be reduced. But in linked list you create node when you need it delete it when you don't need it, like building flats only when someone comes to stay.
Here I have written a program which simply demonstrate a linked list program

#include"stdio.h"
typedef struct node
{
int val;
struct node *next;
} NODE;
NODE *createnode(int val)
{
NODE *tmp=(NODE *)malloc(sizeof(NODE));
    if(tmp)
    {
        tmp->val=val;
        tmp->next=NULL;
        return tmp;
    }
    return NULL;
}
void deletenode(NODE **n,int key)
{
NODE *prev=NULL;
NODE *n1=*n;
while(n1)
{
    if(n1->val==key)
    {
        if(!prev)
        {
            NODE *t=*n;
            (*n)=(*n)->next;
            free(t);
            return;
        }
        else
        {
            prev->next=n1->next;
            return;
        }
    }
    prev=(n1);
    n1=n1->next;
   
}
}
void print(NODE *n)
{
    printf("\nValues in the list : ");
    while(n)
    {
        printf("%d,",n->val);
        n=n->next;
    }
}
void main()
{
NODE *node=NULL,*node1=NULL,*tmp;
int key=0,opt=0;
    while(1)
    {
        printf("\nEnter 1 to add, 2 to delete 3 to print 4 to exit : ");
        scanf("%d",&opt);
        switch(opt)
        {
        case 1:
            printf("\nEnter value : ");
            scanf("%d",&key);
            if(key==-99)
            {
                break;
            }
            if(!node)
            {
                node=createnode(key);
                node1=node;
            }
            else
            {
                tmp=createnode(key);
                node1->next=tmp;
                node1=node1->next;
                tmp=NULL;
            }
            break;
        case 2:
            printf("\nEnter search value : ");
            scanf("%d",&key);
            deletenode(&node,key);
            break;
        case 3:
            print(node);
            break;
        case 4:
            return;
        }
    }
}

No comments: