Program to show implementation of singly linkedlist



/* implementation of singly linkedlist */
#include
#include
#include "linklist.h"

void release(linkedlist *lp)
{
while(lp -> count > 0)
del(lp, lp -> count);
}

node **goto_node(linkedlist *lp, int pos)
{
node *n = lp -> base, **curr = &(lp -> base);
if(pos < 0 || pos > lp -> count)
return NULL;

while(pos > 0)
{
curr = &(n -> next);
n = n -> next;
pos--;
}
return curr;
}

int append(linkedlist *lp, char *data)
{
node **curr = goto_node(lp, lp -> count);
*curr = (node *) malloc(sizeof(node));
if(*curr == NULL)
return FALSE;

strcpy((*curr) -> name, data);
(*curr) -> next = NULL;
lp -> count++;
return TRUE;
}

int insert(linkedlist *lp, int pos, char *data)
{
node **curr = goto_node(lp, pos - 1), *tmp;
if(curr == NULL)
return FALSE;
tmp = *curr;
*curr = (node *) malloc(sizeof(node));
if(*curr == NULL)
return FALSE;

strcpy((*curr) -> name, data);
(*curr) -> next = tmp;
lp -> count++;
return TRUE;
}

int del(linkedlist *lp, int pos)
{
node **curr = goto_node(lp, pos - 1), *tmp;
if(curr == NULL)
return FALSE;
tmp = *curr;
free(*curr);
*curr = tmp -> next;
lp -> count--;
return TRUE;
}

void show(linkedlist *lp)
{
node *n = lp -> base;
while(n != NULL)
{
printf("\n%s", n -> name);
n = n -> next;
}
}

int main(void)
{
int choice, pos;
char value[80];
linkedlist l = { NULL, 0 };
do
{
printf("\n ** SINGLE LINKED LIST **");
printf("\n1. Add\n2. Insert\n3. Remove\n4. Show\n5. Exit\nOption [1 - 5] ? ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nName :");
fflush(stdin);
gets(value);
if(!append(&l, value))
printf( "\nNode creation failed" );
else
printf( "\nNew node created successfully" );
break;
case 2:
printf("\nInsert position ? " );
scanf( "%d", &pos );
printf("\nEnter value :");
fflush(stdin);
gets(value);
if(!insert(&l, pos, value))
printf( "\nNode insertion failed" );
else
printf( "\nNode inserted successfully" );
break;
case 3:
printf("\nDelete position ? " );
scanf( "%d", &pos );
if(!del( &l, pos ))
printf( "\nNode removal failed" );
else
printf("\nNode removed successfully");
break;
case 4:
show(&l);
break;
case 5:
release(&l);
break;
}
}while(choice != 5);

return SUCCESS;
}

No comments:

Post a Comment