Created
January 11, 2021 13:32
-
-
Save aditya-vijaykumar/07c9f1b96a0b3eef92fc2b0b491d5ad2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<stdio.h> | |
#include<stdlib.h> | |
#include<string.h> | |
typedef struct node | |
{ | |
char name[25]; | |
struct node *link; | |
}name; | |
name *head = NULL; | |
int count = 0; | |
void insertName(){ | |
name *ptr, *cur; | |
ptr = (name *)malloc(sizeof(name)); | |
if(ptr == NULL){ | |
printf("Memory Allocation Failed"); | |
return; | |
} | |
char a[25]; | |
printf("Enter name to be stored\n"); | |
scanf("%s", a); | |
strcpy(ptr->name, a); | |
if(head == NULL){ | |
head = ptr; | |
ptr->link = NULL; | |
count++; | |
} else { | |
cur = head; | |
if(strcmp(head->name, ptr->name) > 0){ | |
ptr->link = head; | |
head = ptr; | |
} | |
else if(strcmp(head->name, ptr->name) == 0){ | |
ptr->link = head->link; | |
head->link = ptr; | |
} | |
else { | |
cur = head; | |
for(int i = 0; i < count-1; i++){ | |
int r = strcmp((cur->link)->name, ptr->name); | |
if(r==0){ | |
name *next; | |
next = cur->link; | |
ptr->link = next->link; | |
next->link = ptr; | |
break; | |
} | |
else if(r>0){ | |
ptr->link = cur->link; | |
cur->link = ptr; | |
break; | |
} | |
else if(r<0){ | |
cur = cur->link; | |
continue; | |
} | |
} | |
} | |
count++; | |
} | |
} | |
void deleteName(){ | |
char a[25]; int i; | |
printf("Enter name to be deleted\n"); | |
scanf("%s", a); | |
name *cur; | |
cur = head; | |
if(strcmp(head->name, a) == 0){ | |
head = head -> link; | |
free(cur); | |
count--; | |
printf("Found the name %s and deleted \n", a); | |
}else { | |
for(i =0; i<count-1; i++){ | |
if(strcmp((cur->link)->name, a) == 0){ | |
name *tmp; | |
tmp = (cur->link); | |
cur->link = tmp->link; | |
free(tmp); | |
count--; | |
printf("Found the name %s and deleted \n", a); | |
break; | |
} else { | |
cur = cur-> link; | |
continue; | |
} | |
} | |
} | |
if(i == count-1) | |
printf("The name %s does not exist in the list", a); | |
} | |
void displayName(){ | |
if(head == NULL){ | |
printf("The Name List is empty, nothing to display\n"); | |
return; | |
} | |
name *cur = head; | |
while(cur != NULL){ | |
printf("%s \n", cur->name); | |
cur = cur->link; | |
} | |
} | |
int main() | |
{ | |
int c; | |
while(1){ | |
printf("Enter 1 to insert, 2 to delete, 3 to display and 4 to exit\n"); | |
scanf("%d", &c); | |
switch(c){ | |
case 1: | |
insertName(); | |
break; | |
case 2: | |
deleteName(); | |
break; | |
case 3: | |
displayName(); | |
break; | |
case 4: | |
return 0; | |
default: | |
printf("Invalid input"); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment