asim.syslock.org
Tue 05 Dec 2006.  
Asim’s blog   /   Syslock archive



Home : C/C++

Name : MRU List implementation.
Description : Implements Most Recently Used linked list.

Code :

#include <stdio.h>
#include <string.h>
#include "malloc.h"

struct node {
char name[25];
char key[25];
struct node *nxt;
};

struct node *mru;

void enter (char*,char*);
void view (char*);
void viewall();
void del (char*);

main () {
char nm[25],s[25];int choice;
choice=1;
while (choice!=0) {
printf ("\n Enter choice:- \n 1.Enter \n 2.View \n 3.View structure \n 4.Delete \n 0.Exit \n");
scanf ("%d",&choice);
if (choice==1) { printf("Enter name : ");
scanf ("%s",&nm);
printf("key : ");
scanf ("%s",&s);
enter (nm,s);}
if (choice==2) {printf ("Enter name : ");
scanf ("%s",&nm);
view (nm);}

if (choice==3) viewall ();
if (choice==4) {printf ("Enter name : ");
scanf ("%s",&nm);
del (nm);}




}
}
void enter (char nm[25],char s[25]) {
struct node *temp,*t;int pos;
t=(struct node *)malloc (sizeof (struct node));
if (mru==NULL)
{
mru=t;
}
else
{ t->nxt=mru;
mru=t;
}
strcpy(t->key,s);
strcpy(t->name,nm);



}

void view (char nm[25]) {
int found;struct node *temp,*prev;

found=1;
temp=mru;prev=NULL;
while ((temp!=NULL) && (found!=0)) {
if (strcmp(temp->name,nm)==0)
found=0;
else {
prev=temp;
temp=temp->nxt;
}
}
if (found==1) printf ("Entry not found");
else { printf("\n Name :- %s",temp->name);
printf ("\n Key :- %s",temp->key);
if (prev!=NULL) {
prev->nxt=temp->nxt;
temp->nxt=mru;
mru=temp;
}

}
}

void viewall () {
struct node *temp;
temp=mru;
if (temp==NULL) printf ("No enteries present");
while (temp!=NULL) {
printf (" %s ",temp->name);
temp=temp->nxt;
}
}

void del (char nm[25]) {
int found;struct node *temp,*prev;

found=1;
temp=mru;prev=NULL;
while ((temp!=NULL) && (found!=0)) {
if (strcmp(temp->name,nm)==0)
found=0;
else {
prev=temp;
temp=temp->nxt;
}
}
if (found==1) printf ("Entry not found");
else { printf("\n Entry deleted");
if (prev!=NULL) prev->nxt=temp->nxt;
else mru=temp->nxt;
}
}