Thursday, 28 April 2011

Code for Linked Lists

This is a C code for inserting elements in a linked list at its end, deleting elements from the end.

This code is for the Linux environment written in the vi editor.

Program :
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
struct node{
int data;
struct node *link;
}*start=NULL,*temp,*ptr;void display(){
ptr=start;
printf("Data in the list:\t");
if(start==NULL)
{
printf("List empty");
while(ptr!=NULL)
{
printf("%d\t",ptr->data);
ptr=ptr->link;
}
}void insert_end(){
temp=malloc(sizeof(struct node));
printf("\nEnter data for node \n");
scanf("%d",&temp->data);
if(start==NULL)
{
temp->link=NULL;
start=temp;
}
else
{
ptr=start;
while(ptr->link!=NULL)
{
ptr=ptr->link;
}
ptr->link=temp;
temp->link=NULL;
}
display();
}
void delete_end(){
if(start==NULL)
{
printf("No more nodes in the list");
return;
}
if(start->link==NULL)
{
free(start);
start=NULL;
return;
}
ptr=start;
while(ptr->link!=NULL)
{
temp=ptr;
ptr=ptr->link;
}
temp->link=NULL;
free(ptr);
display();
}
int main(){
int ch;
while(1)
{
system("clear");
printf("\n------Menu --------\n");
printf("\n1.Insert at the end\n");
printf("\n2.Delete from end\n");
printf("\n3.Exit\n");
printf("\nEnter choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
insert_end();
break;
}
case 2:
{
delete_end();
break;
}
case 3:
{
exit(0);
}
}
}
return 0;
}

No comments:

Post a Comment