Google

Wednesday, April 7, 2010

CSC202: Link List

Write a program that can display the following menu:

1. Insert Record
2. Search Record
3. Delete Record
4. Print Record
5. Exit

The user will enter 1, 2,3, 4 or 5. Then the program will perform
the appropriate task. Use link list to implement. Use separate functions
for each of the above.


SOLUTION:

#include "stdio.h"
#include "stdlib.h"
#include "string.h"

struct node
{
char firstname[32];
struct node* next;
};


typedef struct node NODE;

void menu(void);
void insert();
void searchlist();
void deletenode();
void printlist();

NODE *root = NULL;

void main()
{
int choice;

for(;;)
{
menu();
scanf("%d",&choice);
switch(choice)
{
case 1:
insert();
break;

case 2:
searchlist();
break;

case 3:
deletenode();
break;

case 4:
printlist();
break;

default:
return;
}
}
}

void menu()
{
printf("\n\n1. Insert Record\n");
printf("2. Search Record\n");
printf("3. Delete Record\n");
printf("4. Print Record\n");
printf("5. Exit\n\n");
}

void insert()
{
NODE *pointer;

//--- if first node ---
if(root==NULL)
{ //memory allocation
pointer = (NODE*)malloc( sizeof(NODE) );
root = pointer;
}
else
{
pointer=root;
while(pointer->next!=NULL)
{
pointer=pointer->next;
}
pointer->next = (NODE*)malloc( sizeof(NODE) );
pointer=pointer->next;
}

char firstname[32]={0};
puts("Enter firstname: ");
scanf("%s",firstname);
strcpy(pointer->firstname,firstname);
pointer->next=NULL;
printlist();
}

void searchlist()
{
NODE *pointer;
pointer = root;

char firstname[32]={0};
puts("Enter firstname: ");
scanf("%s",firstname);
while(pointer!=NULL)
{
if(strcmp(pointer->firstname,firstname)==0)
{
puts("Found");
printf("Firstname: %s\n",pointer->firstname);
return;
}
//printf("%s -> ",pointer->firstname);
pointer=pointer->next;
}
puts("NO Records Found");
}

void deletenode()
{
NODE *pointer, *previous;
pointer = root;

char firstname[32]={0};
puts("Enter firstname: ");
scanf("%s",firstname);
while(pointer!=NULL)
{
if(strcmp(root->firstname,firstname)==0) {
root = root->next;
printlist();
return;
}
if(strcmp(pointer->firstname,firstname)==0)
{
previous->next=pointer->next;
printlist();
return;
}
//printf("%s -> ",pointer->firstname);
previous=pointer;
pointer=pointer->next;
}
puts("NO Records Found");

}

void printlist()
{
NODE *pointer;
pointer = root;
while(pointer!=NULL)
{
printf("%s -> ",pointer->firstname);
pointer=pointer->next;
}
}