Sunday, 17 June 2012

Singly linked list


#include<stdio.h>
#include<conio.h>
#include<alloc.h>
struct node
{
int data;
struct node *next;
};
void main()
{
struct node *head,*tp,*temp;
int ch,key,value;
clrscr();
head = NULL;
do
{
printf("1.Insert @ first\t 2.Insert @ last\t 3.Insert @ middle\n");
printf("4.Deletion\t 5.Display");
printf("\n\nEnter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: {
            printf("\nenter a no to insert @ first:");
            temp=(struct node*)malloc(sizeof(struct node));
            scanf("%d",&value);
            temp->data=value;
            temp->next=NULL;
            if(head==NULL)
            {
            head=temp;
            }
            else
            {
            temp->next=head;
            head=temp;
            }}
            break;
case 2: {
            printf("\nenter a no to insert @ last:");
            temp=(struct node*)malloc(sizeof(struct node));
            scanf("%d",&value);
            temp->data=value;
            temp->next=NULL;
            if(head==NULL)
            {
             head=temp;
            }
            else
            {
             tp=head;
             while(tp->next!=NULL)
             {
             tp=tp->next;
             }
             tp->next=temp;
            }}
            break;
case 3: {
            printf("\nEnter a no to find:");
            scanf("%d",&key);
            printf("\nenter a no to insert @ middle:");
            temp=(struct node*)malloc(sizeof(struct node));
            scanf("%d",&value);
            temp->data=value;
            temp->next=NULL;
            if(head==NULL)
            head=temp;
            else
            {
             tp=head;
             while(tp!=NULL && tp->data!=key)
             tp=tp->next;
             if(tp!=NULL)
             {
             temp->next=tp->next;
             tp->next=temp;
             }
             else
             printf("\nElement not found...");
            }}
            break;
case 4: {
            printf("\nEnter a no to delete:");
            scanf("%d",&key);
            if(head==NULL)
            printf("\nlist is empty");
            else
            {
            tp=head;
            while(tp!=NULL && tp->data!=key)
            {
            temp=tp;
            tp=tp->next;
            }
            if(tp!=NULL)
            {
            if(tp==head)
            {
            head=head->next;
            free(tp);
            }
            else
            {
            temp->next=tp->next;
            free(tp);
            } }
            else
            printf("\nelement not found");
            }}
            break;
case 5: {
            if(head!=NULL)
            tp=head;
            while(tp!=NULL)
            {
            printf("%d\t",tp->data);
            tp=tp->next;
            }
            printf("\n");
            }break;
default:printf("\nenter correct choice");
            break;
}
}while(ch<=5);
getch();
}

No comments:

Post a Comment