L-27 MCS 275 Mon 19 Mar 2001
Below are the routines we discussed in class:
/* L-27 MCS 275 Mon 19 Mar 2001 Count and lookup, insert and append */
#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 */
int rec_count ( LIST *l );
/* returns the number of elements in a list, recursively */
int itr_count ( LIST *l );
/* returns the number of elements in a list, iteratively */
int lookup ( LIST *l, int k, int n );
/* returns the position of n in the list l if n occurs in the list,
otherwise -1 is returned; call lookup with k equal to one */
LIST *insert ( LIST *l, int n );
/* inserts the number n to the front of the list */
LIST *append ( LIST *first, LIST *last, int n );
/* appends the element n to the end of the list,
returns the new pointer to the last element in the list */
int main()
{
LIST *l,*first,*last;
int n,ind;
printf("Creating list of positive numbers with insert...\n");
l = NULL;
for (;;)
{
printf(" Give a positive number (0 to stop) : ");
scanf("%d", &n);
if (n <= 0)
break;
else
l = insert(l,n);
}
printf("The list of %d elements : ", itr_count(l));
print(l);
printf("\n");
printf("Give element to search for : ");
scanf("%d", &n);
ind = lookup(l,1,n);
if (ind < 0)
printf("The number %d does not occur in the list.\n", n);
else
printf("The number %d occurs at position %d in the list.\n", n, ind);
printf("Creating list of positive numbers with append...\n");
first = NULL;
last = NULL;
for (;;)
{
printf(" Give a positive number (0 to stop) : ");
scanf("%d", &n);
if (n <= 0)
break;
else
{
last = append(first,last,n);
if (first == NULL) first = last;
}
}
printf("The list of %d elements : ", rec_count(first));
print(first);
printf("\n");
return 0;
}
void print ( LIST *l )
{
if (l != NULL)
{
printf(" %d", l->head);
print(l->tail);
}
}
int rec_count ( LIST *l )
{
if (l == NULL)
return 0;
else
return 1 + rec_count(l->tail);
}
int itr_count ( LIST *l )
{
LIST *p;
int cnt=0;
for (p = l; p != NULL; p = p->tail) cnt++;
return cnt;
}
int lookup ( LIST *l, int k, int n )
{
if (l == NULL)
return -1;
else if (l->head == n)
return k;
else
return lookup(l->tail,k+1,n);
}
LIST *insert ( LIST *l, int n )
{
LIST *p;
p = (LIST*)calloc(1,sizeof(LIST));
p->head = n;
p->tail = l;
return p;
}
LIST *append ( LIST *first, LIST *last, int n )
{
LIST *p;
p = (LIST*)calloc(1,sizeof(LIST));
p->head = n;
p->tail = NULL;
if (first == NULL)
last = p;
else
{
last->tail = p;
last = p;
}
return last;
}