单链表c语言版,单链表与顺序表的实现(C语言版)

这两个(单链表和顺序表)的实现方法可以说是最精辟和最容易理解了,而且很完善,很通用!

typedef struct node{

EleType data;

struct node *next;

}ChainNode;

typedef struct{

ChainNode *head;

ChainNode *tail;

}List;

List * CreateList();

void DestoryList(List *);

void ClearList(List *);

int ListAppend(List *,EleType);

int ListInsert(List *,int,EleType);

int ListDelete(List *,int);

int GetElement(List *,int,EleType *);

int TraverseList(List *,int (*)(EleType *));

ChainNode * GetAddr(List *,int);

ChainNode * NewChainNode(EleType);

List * CreateList()

{

List *p;

EleType *data = 0;

p = (List *)malloc(sizeof(List));

if(!p)

{

return 0;

}

p->head = NewChainNode(*data);

p->tail = p->head;

if(!p->head)

{

free(p);

return 0;

}

return p;

}

void DestoryList(List *lp)

{

ClearList(lp);

free(lp->head);

free(lp);

}

void ClearList(List *lp)

{

while(ListDelete(lp,1));

}

int ListAppend(List *lp,EleType data)

{

ChainNode *newp;

newp = NewChainNode(data);

if(!newp)

return 0;

lp->tail->next = newp;

lp->tail = newp;

return 1;

}

int ListInsert(List *lp,int n,EleType data)

{

ChainNode *p;

ChainNode *newp;

p = GetAddr(lp,n-1);

if(!p)

return 0;

newp = NewChainNode(data);

if(!newp)

return 0;

newp->next = p->next;

p->next = newp;

if(!newp->next)

lp->tail = 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 = GetAddr(lp,n);

if(!p1)

return 0;

p->next = p1->next;

if(!p->next)

lp->tail = p;

free(p1);

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;

}

int TraverseList(List *lp,int(* f)(EleType *))

{

ChainNode *p;

int a = 0;

for(p=lp->head->next;p;p=p->next)

{

if(!f(&(p->data)))

return a+1;

a++;

}

return 0;

}

ChainNode * NewChainNode(EleType data)

{

ChainNode *p;

p = (ChainNode *)malloc(sizeof(ChainNode));

if(!p)

return 0;

p->data = data;

p->next = 0;

return p;

}

ChainNode * GetAddr(List *lp,int n)

{

ChainNode *p;

int a;

if(n<0)

return 0;

p = lp->head;

a=0;

while(p&&a

{

p=p->next;

a++;

}

return p;

}

详见附件!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值