Pages

RevenueHits

Search ~~~~

Tuesday, June 28, 2011

Singly Link List Implementation --- C code


Singly Link List Implementation through ~ C programming





struct Node
{
int num;
struct Node *next;
};

struct Node *start=NULL ; 
void addAtEnd(int num)
{
struct Node *t,*j;
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL; 
if(start==NULL)
{
start=t;
}
else
{
j=start;
while(j->next!=NULL)
{
j=j->next;
}
j->next=t;
}
}
void insertAtTop(int num)
{
struct Node *t;
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
if(start==NULL)
{
start=t;
}
else
{
t->next=start;
start=t;
}
}
void insertAtPosition(int num, int pos)
{
struct Node *p1,*p2;
int x;
struct Node *t;
t=(struct Node *)malloc(sizeof(struct Node));
t->num=num;
t->next=NULL;
x=1;
p1=start;
while(x<pos && p1!=NULL)
{
p2=p1;
p1=p1->next;
x++;
}
if(p1==NULL)
{
if(start==NULL)
{
start=t;
}
else
{
p2->next=t;
}
}
else
{
if(p1==start)
{
t->next=start;
start=t;
}
else
{
t->next=p1;
p2->next=t;
}
}
}
void removeFromPosition(int pos)
{
struct Node *p1,*p2;
int x;
if(start==NULL)
{
printf("Invalid Position");
return;
}
x=1;
p1=start;
while(x<pos && p1!=NULL)
{
p2=p1;
p1=p1->next;
x++;
}
if(p1==NULL)
{
printf("Invalid position\n");
return;
}
if(p1==start)
{
start=start->next;
}
else
{
p2->next=p1->next;
}
free(p1);
}
void traverseTopToBottom()
{
struct Node *t;
t=start;
while(t!=NULL)
{
printf("%d\n",t->num);
t=t->next;
}
}
void traverseBottomToTop(struct Node *t)
{
if(t==NULL)
{
return;
}
traverseBottomToTop(t->next);
printf("%d\n",t->num);
}
void main()
{
int ch,num,pos;
while(1)
{
printf("\nEnter yours choice\n");
printf("\n1. Add a node at end \n");
printf("\n2. Insert a node at top \n");
printf("\n3. Insert a node at a position\n");
printf("\n4. Remove a node from a position\n");
printf("\n5. Traverse- Top To Bottom\n");
printf("\n6. Traverse- Bottom To Top\n");
printf("\n7. Exit\n");
scanf("%d",&ch);
if(ch==1)
{
printf("Enter a number to add at end:");
scanf("%d",&num);
addAtEnd(num);
}
if(ch==2)
{
printf("Enter a no. to insert at top:");
scanf("%d",&num);
insertAtTop(num);
}
if(ch==3)
{
printf("Enter a no. to insert:");
scanf("%d",&num);
printf("Enter the position: ");
scanf("%d",&pos);
insertAtPosition(num,pos);
}
if(ch==4)
{
printf("Enter position of the node to remove:");
scanf("%d",&pos);
removeFromPosition(pos);
}
if(ch==5)
{
traverseTopToBottom();
}
if(ch==6)
{
traverseBottomToTop(start);
}
if(ch==7)
{
break;
}
}
}

No comments:

Post a Comment