数据结构之链表

链表
    链表是一种物理存储单元上非连续、非顺序的存储结构
    数据元素的逻辑顺序是通过链表中的指针链接次序实现的
优点
    通过改变指针的指向
    能够灵活快速地增加或者删除元素
缺点
    不能像数组一样随机读取元素
    查询元素时每次都要从头结点根据逻辑顺序进行遍历
总结:
    增删快查询慢
应用
    比如编写一个贪吃蛇的游戏,贪吃蛇用数组来表示显然不合适
    用链表来表示就可以动态的改变其长度

typedef char EleType;
typedef struct node{
	EleType data;
	struct node *next;
}ChainNode;
typedef struct list{
	ChainNode *head;
}List;

ChainNode *NewChainNode(EleType data);
List *CreateList();
ChainNode *GetAddr(List *lp,int n);
int ListAppend(List *lp,EleType data);
int ListInsert(List *lp,int n,EleType data);
int ListDelete(List *lp,int n);
int TraverseList(List *lp,int (*f)(EleType *data));
int GetElement(List *lp,int n,EleType *data);
void ClearList(List *lp);
void ListDestroy(List *lp);

ChainNode *NewChainNode(EleType data){
	ChainNode *p;
	p = (ChainNode *)malloc(sizeof(ChainNode));
	if(!p){
		return 0;
	}
	p->data = data;
	p->next = 0;
	return p;	
}
List *CreateList(){
	ChainNode *p;
	List *lp;
	EleType *data = 0;
	lp = (List *)malloc(sizeof(List));
	if(!lp){
		return 0;
	}
	p = NewChainNode(*data);
	if(!p){
		return 0;
	}
	lp->head = p;
	if(!lp->head){
		free(lp);
		return 0;
	}		
	return lp;
}
ChainNode *GetAddr(List *lp,int n){
	ChainNode *p;
	int a = 0; 
	if(n < 0){
		return 0;
	}
	p = lp->head;
	while(p&&a < n){
		p = p->next;
		a++;
	}
	return p;
}
int ListAppend(List *lp,EleType data){
	ChainNode *p;
	ChainNode *newp;
	newp = NewChainNode(data);	
	if(!newp){
		return 0;
	}
	for(p = lp->head;p->next;p = p->next){}
	p->next = newp;
	return 1;
}
int ListInsert(List *lp,int n,EleType data){
	ChainNode *p;
	ChainNode *newp;
	newp = NewChainNode(data);
	if(!newp){
		return 0;
	}
	p = GetAddr(lp,n-1);
	if(!p){
		return 0;
	}
	newp->next = p->next;
	p->next = newp;
	return 1;		
}
int ListDelete(List *lp,int n){
	ChainNode *p;
	ChainNode *p1;
	if(!lp->head->next){
		return 0;
	}	
	p = GetAddr(lp,n-1);
	if(!p){
		return 0;
	}
	p1 = p->next;
	p->next = p->next->next;
	free(p1);
	return 1;
}
int TraverseList(List *lp,int (*f)(EleType *data)){
	ChainNode *p;
	int a = 0;
	for(p = lp->head->next;p;p = p->next){
		if(!f(&(p->data))){
			return a+1;
		}
		a++;
	}
	return 1;
}
int GetElement(List *lp,int n,EleType *data){
	ChainNode *p;
	p = GetAddr(lp,n);
	if(!p){
		return 0;
	}
	*data = p->data;
	return 1;	
}
void ClearList(List *lp){
	while(ListDelete(lp,1)){}
}
void ListDestroy(List *lp){
	ClearList(lp);
	free(lp->head);
	free(lp);
}



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值