5/01/2009

C Program Create a Linked List


/*C Program Create a Linked List*/
#include<stdio.h>
#include<malloc.h>
struct node
{
    int info;
    struct node *link;
};
struct node *getnode()
{
    return (struct node*)malloc(sizeof(struct node));
}
struct node *insert (int item,struct node *first)
{
    struct node *temp;
    temp=getnode();
    temp->info=item;
    temp->link=first;
    return temp;
}
void display(struct node *temp)
{
    printf("contents of Linked List\n");
    while(temp!=NULL)
    {
        printf("%d\t", temp->info);
        temp=temp->link;
    }
    printf("\n");
}
void main()
{
    struct node*first=NULL;
    int ch,item;

    while(1)
    {
        printf("1.insert\t2.display\n");
        printf("enter the choice:\n");
        scanf("%d",&ch);
        switch(ch)
        {
        case 1:
            printf("enter the item to be inserted:\n");
            scanf("%d",&item);
            first=insert(item,first);
            break;
        case 2:
            display(first);
            break;
        default:
            exit(0);
        }

    }
}
Out Put:
1.insert        2.display
enter the choice:
1
enter the item to be inserted:
1
1.insert        2.display
enter the choice:
1
enter the item to be inserted:
2
1.insert        2.display
enter the choice:
1
enter the item to be inserted:
3
1.insert        2.display
enter the choice:
1
enter the item to be inserted:
4
1.insert        2.display
enter the choice:
1
enter the item to be inserted:
5
1.insert        2.display
enter the choice:
2
contents of Linked List
5       4       3       2       1
1.insert        2.display
enter the choice:
3

No comments:

Post a Comment