Pages

Create single link list and insert a new node in link list.

Thursday 6 June 2013

#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
struct node
{
       int data;
       struct node *link;
};
struct node *n, *first, *this1, *pre;
int main()
{
    char ch;
    int position;
    first=NULL;
    printf("Enter q to quit: ");
    ch=getche();
    while(ch!='q')
    {
           n=(struct node *)malloc(sizeof(struct node));
           printf("\nEnter data to store in node: ");
           scanf("%d", &n->data);
           n->link=NULL;
           if(first==NULL)
           {
                  first=n;
           }
           else
           {
                  this1=first;
                  while(this1->link!=NULL)
                  {
                          this1=this1->link;
                  }
                  this1->link=n;
           }
           printf("Press q to quit: ");
           ch=getche();
    }
    printf("\n");
    this1=first;
           while(this1!=NULL)
           {
                   printf("%d %d\n", this1->data, this1->link);
                   this1=this1->link;
           }
           //insertion
    printf("where you want to enter number: ");
    scanf("%d", &position);
if(first->data==position)
{
             n=(struct node *)malloc(sizeof(struct node));
             printf("Enter number: ");
             scanf("%d", &n->data);
             n->link=first;
             first=n;
}
else
{
    this1=first;
    while(this1!=NULL && position!=this1->data)
    {
             pre=this1;
             this1=this1->link;
    }
    if(this1==NULL)
    printf("Number is not found.");
    else
    {
       
             n=(struct node *)malloc(sizeof(struct node));
             printf("Enter number: ");
             scanf("%d", &n->data);
             n->link=this1;
             pre->link=n;
    }
}
    //treversing after insertion
    this1=first;
           while(this1!=NULL)
           {
                   printf("%d\n", this1->data);
                   this1=this1->link;
           }
    getch();
   
}
 

Search Box

Most Reading

Contact Form

Name

Email *

Message *