//a program to perform the following operations on a linked list
#include < stdio.h> #include < stdlib.h> //node of the linked list typedef struct Node{ int data; struct node *link; }Node; //handle of the list. the head pointer in in points towards the first node of the list typedef struct List{ Node *length; int length; }List; //create an empty list List* create_list(); //insert a new node at the beginning of the linked list void insert_beginning(List *list,int data); //delete the first node having the element "data" //No operation if there is no such node void delete_element(List *list,int data); //display the elements of the linked list separated by spaces on a single line void disp_list(List *list); //delete the linked list along with any nodes in it void delete_list(List *list); int main() { int choice=1; int element; List *list=create_list(); while(choice>0 && choice<4) { scanf("%d",&choice);// 1:insert an element in the beginning. // 2:delete a specified element. // 3:display the list. switch(choice){ case 1: scanf("%d",&element); //enter the element to be inserted insert_beginning(list,element); break; case 2: scanf("%d",&element); //enter the element to be deleted delete_element(list,element); break; case 3: disp_list(list); break; } } delete_list(list); return 0; } List* create_list() { List *list; list=(List*)malloc(sizeof(List)); list->head=NULL; list->length=0; return list; } void insert_beginning(List *list,int data) { Node *temp; temp=(Node*)malloc(sizeof(Node)); temp->data=data; if(list->head==NULL){ temp->link=NULL; list->head=temp; } else{ temp=list->head; list->head=temp; } list->length++; temp=NULL; } void delete_element(List* list,int data) { Node *iter=list->head,*temp=list->head; int i=1; while(iter!=NULL) { if(temp->data==data){ if(i<2){ list->head=temp->link; } else{ iter->link=(Node *)temp->link; } free(temp);list->length--; } else{ temp=temp->link;i++; if(i>2){ iter=iter->link; } } }iter=NULL;temp=NULL; } void disp_list(List *list) { Node *temp; if(list->head!=NULL){ temp=list->head; while(temp->link!=NULL){ printf("%d ",temp->data); temp=temp->link; } printf("%d\n",temp->data); }temp=NULL; } void delete_list(List *list) { Node *temp=NULL,*iter=list->head; while(iter!=NULL && iter->link!=NULL){ temp=iter; iter=iter->link; free(temp); } free(iter);free(list); }