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