[ create a new paste ] login | about

Link: http://codepad.org/0NPX55xg    [ raw code | output | fork ]

C, pasted on Jul 10:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct ListNode_ {struct ListNode_ *prev; int n;} ListNode;
typedef struct List_ {int isempty; struct ListNode_ tail;} List;

void *EMAlloc(size_t size)
{
	void *p = malloc(size);
	
	if (!p) {
		perror(NULL);
		exit(1);
	}
	return p;
}

List *CreateList(void)
{
	List *l = EMAlloc(sizeof(List));
	
	l->isempty = 1;
	return l;
}

void AddList(List *l, int n)
{
	if (l->isempty) {
		l->tail.prev = NULL;
	} else {
		ListNode *ln = EMAlloc(sizeof(ListNode));
		
		memcpy(ln, &l->tail, sizeof(ListNode));
		l->tail.prev = ln;
	}
	l->tail.n = n;
	l->isempty = 0;
}

void PrintListNode(ListNode *le)
{
	if (le) {
		PrintListNode(le->prev);
		printf("%d->", le->n);
	}
}

void PrintList(List *l)
{
	if (l->isempty) {
		printf("empty\n");
	} else {
		PrintListNode(l->tail.prev);
		printf("%d\n", l->tail.n);
	}
}

int main(void)
{
	List *l = CreateList();
	
	PrintList(l);
	AddList(l, 1); PrintList(l);
	AddList(l, 2); PrintList(l);
	AddList(l, 3); PrintList(l);
	AddList(l, 4); PrintList(l);
	return 0;
}


Output:
1
2
3
4
5
empty
1
1->2
1->2->3
1->2->3->4


Create a new paste based on this one


Comments: