C Program to implement singly linked list

This program implements linked list in c.  A linked list is a collection of nodes. Each node contains a data part and a pointer to the next node.The advantage of linked list is that the data items need not be stored in contiguous locations in the memory. This program implements insertion, deletion and display of a linked list.

Program


#include<stdio.h>

#include<conio.h>

struct node

{

    int data;

    struct node *next;

}*start=NULL,*p,*traverse,*temp;

void main()

{

    int ch,item;

    printf("1.Insert Begin\n2.Insert after\n3.Delete Begin");

    printf("\n4.Delete after\n5.Display\n6.Exit\nEnter Your Choice");

    scanf("%d",&ch);

    while(ch!=6)

    {

    switch(ch)

    {

        case 1:

        p=(struct node*)malloc(sizeof(struct node));

        printf("Enter the data\n");

        scanf("%d",&item);

        p->data=item;

        p->next=start;

        start=p;

        break;

        case 2:

        printf("Insert after which item\n");

        scanf("%d",&item);

        traverse=start;

        while(traverse->data!=item)

        traverse=traverse->next;

        temp=traverse->next;

        p=(struct node*)malloc(sizeof(struct node));

        printf("Enter the data\n");

        scanf("%d",&item);

        p->data=item;

        traverse->next=p;

        p->next=temp;

        break;

        case 3:

        temp=start->next;

        free(start);

        start=temp;

        break;

        case 4:

        printf("Delete after which item");

        scanf("%d",&item);

        traverse=start;

        while(traverse->data!=item)

        traverse=traverse->next;

        p=traverse->next;

        temp=p->next;

        traverse->next=temp;

        free(p);

        break;

        case 5:

        traverse=start;

        printf("\nCurrent List is\n");

        while(traverse!=NULL)

        {

            printf("%d -> ",traverse->data);

            traverse=traverse->next;

        }

        break;

    }

    printf("\n\n1.Insert Begin\n2.Insert after\n3.Delete Begin");

    printf("\n4.Delete after\n5.Display\n6.Exit\nEnter Your Choice");

    scanf("%d",&ch);

    }

}

No comments: