Pages

Saturday, April 24, 2010

Simple Linked list

#include
#include
struct node{
int val;
struct node *next; // to store the next value
};

void insert(struct node**);
void delete(struct node**);
void traverse(struct node**);
int main()
{
struct node *head=NULL;
int opt=0;

while(1){
printf("Select an option \n 1.Insert 2.Delete 3.Exit 4. Traverse\n");
scanf("%d",&opt);
switch(opt){
case 1:{insert(&head); break; }
case 2:{delete(&head);break;}
case 3:{ exit(0);break; }
case 4:{traverse(&head);}
default:{printf("Invalid no");}
}
}
}


void traverse(struct node **head) // function to traverse
{ // input Address of head
printf("\n");
struct node *ptr;
if(*head==NULL){
printf("List Empty");
return;
}
ptr=*head;
while(ptr!=NULL){
printf(" %d",ptr->val);
ptr=ptr->next;
}
printf("\n");

}

void insert(struct node **head) // function to insert new node
{ // input address of head
struct node *ptr,*temp;

ptr=(struct node*)malloc(sizeof(struct node));
if(ptr==NULL){
printf("Allocation failed\n");
return;
}
printf("Enter an integer value\n");
scanf("%d",&ptr->val);
temp=*head;
if(temp==NULL){
ptr->next=NULL;
*head=ptr;
return;
}
while(temp->next!=NULL)temp=temp->next;
temp->next=ptr;
}

void delete(struct node **head) // function to delete a node
{ // input address of head
struct node *ptr=*head;
struct node *prevptr=NULL;
int val;
if(*head==NULL){
printf("List empty");
return;
}
printf("Enter the value to delete\n");
scanf("%d",&val);
while((ptr->val!=val)&&(ptr->next!=NULL)){
prevptr=ptr;
ptr=ptr->next;
}

if(ptr->val!=val){
printf("Value not found\n");
return;
}
if(prevptr==NULL){ //if selected element has no previous element
*head=ptr->next;
free(ptr);
return;

}
prevptr->next=ptr->next;
traverse(head);
free(ptr);
}

No comments:

Post a Comment