Sunday, January 9, 2011

C source code : Linked list operations

#include <stdio.h>
#include <stdlib.h>
typedef struct list* node;

struct list {
    node next;
    int data;
};

node create_node(int val)
{
    node new_node=(node)malloc(sizeof(node));
    new_node->data=val;
    return new_node;
}
void insert_node(node head, int val, int pos)
{
    while(head->data!=pos)
    {
        head=head->next;

    }
    node tmp=head->next;
    head->next=create_node(val);
    head->next->next=tmp;

}

void print_list(node head)
{
    while(head!=NULL)
    {
        printf("%d - ",head->data);
        head=head->next;
    }
}

int main()
{
    int i;
    printf("Linked List operation\n");
    node head=create_node(0);
    node start=head;
    for(i=1;i<=10;i++)
    {
        head->next=create_node(i);
        head=head->next;
    }
    head->next=NULL;
    print_list(start);
    printf("\n Print the list after insertion");
    insert_node(start,15,5);
    printf("\n");
    print_list(start);
    return 0;
}

No comments:

Post a Comment