L-28 MCS 275 Wed 21 Mar 2001
Below are the routines we discussed in class:
/* L-28 MCS 275 Wed 21 Mar 2001 insertion and deletion */
#include <stdio.h>
#include <stdlib.h>
typedef struct list LIST;
struct list
{
int head;
LIST *tail;
};
void print ( LIST *l );
/* prints the elements in a list */
LIST *create ( int n );
/* returns a list that contains n */
LIST *insert ( LIST *current, LIST *next, int n );
/* inserts the number n in between current and next,
returns the new value for next */
LIST *delete ( LIST *current, LIST *next );
/* deletes the element where next is pointing to,
returns the new value for next */
void destroy ( LIST *l);
/* destroys the list, freeing the allocated memory */
int main()
{
LIST *l,*current,*next;
int n,ind;
printf("Creating list of positive numbers...\n");
l = NULL;
for (;;)
{
printf(" Give a positive number (0 to stop) : ");
scanf("%d", &n);
if (n <= 0)
break;
else
{
if (l == NULL)
l = create(n);
else if (l->tail == NULL)
{
l->tail = create(n);
current = l;
next = l->tail;
}
else
next = insert(current,next,n);
}
}
printf("The list of elements : ");
print(l);
printf("\n");
next = delete(current,next);
printf("The list of elements after one delete : ");
print(l);
printf("\n");
destroy(l);
printf("List has been destroyed. Bye bye.\n");
return 0;
}
void print ( LIST *l )
{
if (l != NULL)
{
printf(" %d", l->head);
print(l->tail);
}
}
LIST *create ( int n )
{
LIST *l;
l = (LIST*)calloc(1,sizeof(LIST));
l->head = n;
l->tail = NULL;
return l;
}
LIST *insert ( LIST *current, LIST *next, int n )
{
LIST *p;
p = (LIST*)calloc(1,sizeof(LIST));
p->head = n;
p->tail = next;
current->tail = p;
next = p;
return next;
}
LIST *delete ( LIST *current, LIST *next )
{
current->tail = next->tail;
free(next);
return current->tail;
}
void destroy ( LIST *l )
{
if (l != NULL)
{
destroy(l->tail);
free(l);
}
}