1. 程式人生 > >《資料結構與演算法分析-c語言描述》第三章表ADT程式碼補全

《資料結構與演算法分析-c語言描述》第三章表ADT程式碼補全

這本書講的很不錯(英文版)也讓我第一次懷疑了自己是否是中國人,翻譯啊真的有時候看不懂有時還要看英文版的才能看懂這個意思而且書上的程式碼給的不全故放部落格上給自己複習和造福大眾(???)

#include<stdio.h>
#include<stdlib.h> 
struct node;
typedef struct node *LIST;
 struct node{
 	int e;
 	LIST next;
 };
LIST createlist();
LIST makeempty(LIST);
void deletlist(LIST);
LIST header(LIST);
LIST advance(LIST);
int retrieve(LIST);
int isempty(LIST);
int islast(LIST,LIST);
LIST find(int,LIST);
void delet(int,LIST);
void insert(int,LIST,LIST);
LIST findprevious(int,LIST);
LIST first(int,LIST);
void printlist(LIST);
int isempty(LIST L){
	return L->next==NULL;
}
int islast(LIST p,LIST L){
	return p->next==NULL;
} 
LIST find(int x,LIST L){
	LIST p=L->next;
	while(p!=NULL&&p->e!=x)
	p=p->next;
	return p;
}
void delet(int x,LIST L){
	LIST p,tem;
	p=findprevious(x,L);
	if(!islast(p,L)){
		tem=p->next;
		p->next=tem->next;
		free(tem);
	}
}
LIST findprevious(int x,LIST L){
	LIST p=L;
	while(p->next!=NULL&&p->next->e!=x)
	p=p->next;
	return p;
}
void insert(int x,LIST L,LIST p){
	LIST tem;
	tem=(LIST)malloc(sizeof(struct node));
	if(tem==NULL)
	{
		puts("error");
		exit(1);
	}
	tem->e=x;
	tem->next=p->next;
	p->next=tem;
}
LIST first(LIST L){
    return L->next;//next的原因是包含了表頭表頭沒有資料
}
LIST makeempty(LIST L){
	if(L!=NULL){
		deletlist(L);
		L=(LIST)malloc(sizeof(struct node));
	}
	else if(L==NULL){
		puts("out of memory");
	}
	L->next=NULL;
	return L;
}
LIST header(LIST L){
	return L;
}
LIST advance(LIST p){
	return p->next;
}
int retrieve(LIST p){
    return p->e;	
}
void deletlist(LIST L){
	LIST p,tem;
	p=L->next;
	L->next=NULL;
	while(p!=NULL){
		tem=p->next;
		free(p);
		p=tem;
	}//不包括表頭 
}
LIST createlist(){
	LIST l=(LIST)malloc(sizeof(struct node));
	if(l==NULL){
		puts("memory error!");
		exit(1);
	}
	l->next=NULL;
	return l;
}
void printlist(LIST L){
	LIST p=L->next;
	while(p!=NULL){
		printf("%d",p->e);
		p=p->next;
	}
}