/*
 * Faculty of Applied Science and Engineering, University of Toronto
 * CSC181: Introduction to Computer Programming, Fall 2000
 *
 * Assignment: 3
 * File: list.c
 * Author: Ray Ortigas (rayo@dgp.toronto.edu)
 * Contains: Function definitions for List module.
 */

#include <assert.h>
#include <stdlib.h>
#include "list.h"

/* Returns an empty list. */
ListPtr listInit(void) {
	ListPtr result = malloc(sizeof(List));
	assert(result != NULL);

	result->front = NULL;
	result->size = 0;
	return result;
}

/* Returns the size of the given list. */
int listSize(const ListPtr l) {
	assert(l != NULL);
	return l->size;
}

/* Returns the element at index i in list l. The given index must be
   between 0 and n-1 inclusive, where n is the size of the list. */
void* listGet(const ListPtr l, const int i) {
	int j;
	ListNodePtr current;
	assert(l != NULL);
	assert(0 <= i && i < l->size);

	for (j = 0, current = l->front; 
		j != i && current != NULL; 
		j++, current = current->next) ;

	return current->data;
}

/* Adds element d to list l, making it the last element. */
void listAppend(ListPtr l, void* d) {
	ListNodePtr newNode;
	assert(l != NULL);

	newNode = malloc(sizeof(ListNode));
	assert(newNode != NULL);

	newNode->data = d;
	newNode->next = NULL;

	if (l->front == NULL) {
		l->front = newNode;
	}
	else {
		ListNodePtr current = l->front;
		while (current->next != NULL) {
			current = current->next;
		}
		current->next = newNode;
	}

	l->size++;
}
