Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//This is my(Brandon Tennant's) implementation of a linked list in C.
//Enjoy.
struct person
{
char name[80];
struct person *next;
};
typedef struct person PERSON;
typedef PERSON* LINK;
void add(LINK ptr, LINK data);
void remove(LINK ptr, char *name);
void print(LINK ptr);
int main()
{
LINK head=NULL;
LINK person=(PERSON*)malloc(sizeof(PERSON));
int selection=0;
char name[80];
printf("Hello. Enter your selection.\n");
while(1)
{
printf("1. Add\n2.Delete\n3.Print\n4.Exit\n");
fflush(stdin);
scanf("%d",&selection);
switch(selection)
{
case 1:
printf("Enter a name.\n");
fflush(stdin);
gets(name);
strcpy(person->name,name);
add(head,person);
break;
case 2:
printf("Enter the name you wish to delete.\n");
fflush(stdin);
gets(name);
remove(head,name);
break;
case 3:
print(head);
break;
case 4:
return 0;
default:
printf("Invalid selection.\n");
}
}
return 0;
}
void add(LINK head, LINK data)
{
//Puts the new entry in alphabetical order
LINK current=head;
LINK insert=data;
LINK previous=head;
while(current->next!=NULL)
{
if(strcmp(current->name,insert->name)>0)
{
insert->next=previous->next;
previous->next=insert;
break;
}
previous=current;
current=current->next;
}
}
void remove(LINK head, char *name)
{
LINK current=head;
LINK previous=current;
while(current->next!=NULL)
{
if(strcmp(current->name,name)==0)
{
previous->next=current->next;
free(current);
}
}
}
void print(LINK head)
{
LINK current=head;
while(current->next!=NULL)
{
printf("%s\n",current->name);
}
}