Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  linked list
Language: C/C++
Code:
#include <stdio.h>
#include<stdlib.h>

struct node

{

     int pid;
     struct node *next;
};

typedef struct node n;

n *last =  NULL;
n *first = NULL;

void insert(void);
void display(void);
void delete(void);

int main()
{
     int i;
     while(1)
     {
          printf("Enter choice\n");
          printf("1. Insert 2.Display  3.Delete 4.Exit\n");
          scanf("%1d",&i);
          switch(i)
          {
               case 1 : insert();  break;
               case 2 : display(); break;
               case 3 : delete();  break;
               case 4 : exit(0);
          }
     }
}

void insert()

{
     n *temp=NULL ;
     temp = (n *) malloc(sizeof(n));
     printf("\nEnter the value \n");
     scanf("%d", &temp->pid);
     temp->next = NULL ;
     if(last==NULL)
     {
          last  = temp ;
          first = temp;
     }
     else
     {
          last->next = temp ;
          last = temp ;
     }
}

void display()
{
     n *t=NULL ;
     t = first ;
     while(t != NULL)
     {
          printf("%d \t->",t->pid);
          t = t->next ;
     }
}

void delete()
{
     int i;
     n *tmp=NULL, *t=NULL;
     printf("\nEnter value to be deleted \n");
     scanf("%d", &i);
     for(t=first;t != NULL;t=t->next)
     {
          if(first->pid==i)
          {
               tmp = first;
               first = first->next;
               free(tmp);
               tmp = NULL;
          }
          else if(t->pid==i)
          {
               
               for(tmp=first;tmp != t;tmp=tmp->next)
               {}
               tmp->next = t->next;
               free(t);
               t = NULL;
          }
          else if(last->pid ==i)
          {
               
               for(tmp=first;tmp != last;tmp=tmp->next)
               {}
               free(last);
               last=tmp;
               tmp->next = NULL;
          }
     } 
}
Comments: