view List.c @ 0:5b089096921f

first commit.
author kent <kent@cr.ie.u-ryukyu.ac.jp>
date Fri, 18 Dec 2009 21:57:05 +0900
parents
children aef83aed7a07
line wrap: on
line source

#include<stdlib.h>

#include"List.h"

List *
_listAddFirst(List* top, void *data)
{
	List *newlist;
	if (!top) {
		newlist = malloc(sizeof(struct _List));
		newlist->data = data;
		newlist->next = newlist;
		newlist->prev = newlist;
		return newlist;
	}
	List *last = top->prev;

	newlist = malloc(sizeof(struct _List));
	newlist->data = data;
	newlist->next = top;
	newlist->prev = last;

	top->prev = newlist;
	last->next = newlist;
	return newlist;
}

List *
_listRemove(List *top, void *data)
{
	List *t;
	if (top->data==data) {
		if (top->next==top) {
			free(top);
			return NULL;
		}
		List *newtop = top->next;
		top->next->prev = top->prev;
		top->prev->next = top->next;
		free(top);
		return newtop;
	}
	for (t=top->next; t!=top; t=t->next) {
		if (t->data==data) {
			t->next->prev = t->prev;
			t->prev->next = t->next;
			free(t);
			return top;
		}
	}
	return top;
}

void *
_listGetnthData(List *top, int n)
{
	List *t;

	for (t=top; n>0; n--) {
		t = t->next;
		if (t==top) return NULL;
	}

	return t->data;
}

void
_listApply(List *top, ApplyFn fn, void *arg) {
	List *t = top;
	do {
		fn(t->data, arg);
		t = t->next;
	} while ( t!=top );
}