Friday, September 24, 2010

DSA EX.NO.1a IMPLEMENTATION OF SINGLY LINKED LIST

EX.NO.1a         IMPLEMENTATION OF SINGLY LINKED LIST
                           

AIM:
         
          To write a c program to implement singly linked list.

ALGORITHM:

Step 1: Start the program.

Step 2: Declare a  structure  named as  node with  two fields, one  is data
field  and  another  one  address field , address   field  must  be a  pointer pointing  to next  node.

Step 3: CREATION:
          a. Get the size of lists that has to be created.
          b. Allocate memory space for each node.
          c. Create two pointers to point first node link all other nodes using
              pointers.

Step 4: INSERTION:
          a. Allocate memory space for new node.
          b. Get the position where the new node wants to be  inserted.
          c. Change the links.

Step 5: DELETION:
          a. Get the position of the node that has to be deleted.
          b. Change the links.

Step 6: DISPLAY:
          a. Check weather the list is empty or not.
          b. If list is not empty print the data until the address field is null.

Step 7: Stop the process.





PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdio.h>
struct node
{
int data;
struct node*next;
};
struct node*start,*p,*new1;
int item,i,pos,n,num,null;
void display();
void create()
{
printf("Enter the size of list:");
scanf("%d",&n);
{
new1=(struct node*)malloc(sizeof(struct node));
printf("enter the data");
scanf("%d",&item);
new1->data=item;
new1->next=NULL;
if(i==1)
{
start=new1;
p=new1;
}
else
{
p->next=new1;
p=new1;
}
}
display();
}
void insert()
{
p=start;
printf("enter the position");
scanf("%d",&pos);
new1=(struct node*)malloc(sizeof(struct node));
printf("\n enter the data");
scanf("%d",&item);
new1->data=item;
new1->next=NULL;
for(i=1;i<pos;i++)
p=p->next;
new1->next=p->next;
p->next=new1;
n=n+1;
display();
}
void delet()
{
printf("enter the position");
scanf("%d",&pos);
p=start;
for(i=1;i<pos;i++)
p=p->next;
p->next=p->next->next;
printf("node deleted");
n=n-1;
display();
}
void search()
{
p=start;pos=0;
printf("Enter the demand to be found");
scanf("%d",&num);
for(i=1;i<n;i++)
{
if(p->data==num)
{
printf("Elements is found at %d position\n",i-1);
pos=i;
break;
}
else
p=p->next;
}
if(pos==0)
printf("\nElement not found");
}
void display()
{
p=start;
for(i=1;i<=n;i++)
{
printf("%d->",p->data);
p=p->next;
}
printf("NULL");
}
void main()
{
int c;
clrscr();
for(;;)
{
printf("........MENU.........");
printf("\n1.create");
printf("\n2.insert");
printf("\n3.delete");
printf("\n4.search");
printf("\n5.display");
printf("\n6.exit");
printf("\nEnter the choice");
scanf("%d",&c);
switch(c)
{
case 1:create();break;
case 2:insert();break;
case 3:delet();break;
case 4:search();break;
case 5:display();break;
case 6:exit(0);break;
default:printf("Enter correct choice");
}
}