1. 程式人生 > >線性表-單鏈表的基本操作

線性表-單鏈表的基本操作

結構:

typedef struct lnode {
	elemtype data;
	struct lnode *next;
}lnode,*linklist;

初始化:

status initlist(linklist *l) {
	*l = malloc(sizeof(lnode));
	if (!*l) return ERROR;
	(*l)->next = NULL;
	return OK;
}

銷燬:

status destroylist(linklist *l) {
	linklist p;
	while (*l) {
		p = (*l)->next;
		free(*l);
		*l = p;
	}
	return OK;
}

插入節點:

status listinsert(linklist l, int i, elemtype e) {
	int j = 0;
	linklist p = l;
	linklist new;
	while (p&&j<i - 1) {
		p = p->next;
		j++;
	}
	if (!p || j>i - 1)return ERROR;
	new = malloc(sizeof(lnode));
	if (!new) return ERROR;
	new ->next = p->next;
	p->next = new;
	new->data = e;
	return OK;
}

刪除節點:

status listdelete(linklist l, int i, elemtype *e) {
	linklist p = l, q;
	int j = 0;
	while (j < i - 1 && p->next) {
		p = p->next;
		j++;
	}
	if (j > i - 1 || !p->next) return ERROR;
	q = p->next;
	p->next = q->next;
	*e = q->data;
	free(q);
	return OK;
}

取得某個節點:

status getelem(linklist l,int i,elemtype *e){
	linklist p = l->next;
	int j = 1;
	while (j < i&&p) {
		j++;
		p = p->next;
	}
	if (j > i || !p) return ERROR;
	*e = p->data;
	return OK;
}

清空單鏈表:

status clearlist(linklist l) {
	linklist p = l->next, q;
	while (p) {
		q = p->next;
		free(p);
		p = q;
	}
	l->next = NULL;
	return OK;
}

建立連結串列-頭插法:

status createlist(linklist l, int n) { //head insert
	linklist p;
	while (n-- > 0) {
		p = malloc(sizeof(lnode));
		if (!p) return ERROR;
		p->next = l->next;
		l->next = p;
		scanf("%d", &p->data);
	}
	return OK;
}

建立連結串列-尾插法:

status createlist1(linklist l, int n) { //tail insert
	linklist p, r;
	r = l;
	while (n-- > 0) {
		p = malloc(sizeof(lnode));
		if (!p) return ERROR;
		r->next = p;
		r = p;
		scanf("%d", &p->data);
	}
	r->next = NULL;
	return OK;
}

單鏈表長度:

int listlength(linklist l) {
	linklist p = l->next;
	int i = 0;
	while (p) {
		i++;
		p = p->next;
	}
	return i;
}

列印單鏈表:

void print(elemtype e) {
	printf("%d\n", e);
}

status listtraverse(linklist l, void(*vi)(elemtype)) {
	linklist p = l->next;
	while (p) {
		vi(p->data);
		p = p->next;
	}
	return OK;
}
對於複雜的結構,只需要修改print函式