Monday, September 20, 2010

Single Linked List Example - Add/Delete

Here is the sample program, I have written to explain the singly linked list. This has three functions, one to insert to the list at the head, which is pretty easy by making the new item as the head, and other one to remove from the list when the data is found, 3rd one to insert to the tail of the list, in this case you need to traverse till the end of the list and then insert the item there.

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

typedef struct node_type {
    int data;
    struct node_type *next;
} node;

node *list_head = NULL;

void insert_list(node **plist_head, int data)
{
    node *item = (node *)malloc(sizeof(node));
    item->data = data;
    item->next = *plist_head;
    *plist_head = item;
}

void insert_list_tail(node **plist_head, int data)
{
    node **list_ptr = plist_head;
    node *item = (node *)malloc(sizeof(node));
    item->data = data;
    item->next = NULL;

    while(*list_ptr) 
        list_ptr = &(*list_ptr)->next;

    *list_ptr = item;
}

void show_list(node **list_head)
{
    node **list_ptr = list_head;
    while(*list_ptr)
    {    
        printf("%d\t", (*list_ptr)->data);
        list_ptr = &(*list_ptr)->next;
    } 
    printf("\n");
}

void remove_list(node **plist_head, int data)
{
    node **list_ptr = plist_head;
    while(*list_ptr)
    {
        if((*list_ptr)->data == data)
        {
            node *tmp = *list_ptr;
            *list_ptr = (*list_ptr)->next;
            free(tmp);
            break;
        }
        list_ptr = &(*list_ptr)->next;
    }
}

main()
{
    show_list(&list_head);
    insert_list(&list_head, 2);
    show_list(&list_head);
    insert_list(&list_head, 5);
    show_list(&list_head);
    insert_list(&list_head, 9);
    show_list(&list_head);
    insert_list(&list_head, 1);
    show_list(&list_head);
    remove_list(&list_head, 9);
    show_list(&list_head);
    remove_list(&list_head, 2);
    show_list(&list_head);
    insert_list_tail(&list_head, 8);
    insert_list_tail(&list_head, 12);
    show_list(&list_head);
}

Hope this will help someone who just has just started learning Linked list in C, let me know if something is not clear.

No comments:

Post a Comment