您的位置:首页 > 其它

判断链表是否为空并且求链表长度

2012-08-10 00:00 197 查看
#include<stdio.h>

#include<stdlib.h>

#include<malloc.h>

struct node

{

int data;

struct node *pnext;

};

struct node *creat_list();

void traverse_list(struct node *phead);

bool is_empty(struct node *phead);

int lenght_list(struct node *phead);

int main()

{

struct node *phead;

phead=creat_list();

traverse_list(phead);

if(is_empty(phead))

printf("链表不为空!\n");

else

printf("链表为空!\n");

int len=lenght_list(phead);

printf("链表的节点个数为:%d\n",len);

return 0;

}

//创建链表函数

struct node *creat_list()

{

struct node *phead,*ptail,*pnew;

phead=(struct node *)malloc(sizeof(struct node));

ptail=phead;

ptail->pnext=NULL;

if(NULL==phead)

{

printf("分配内存失败,终止程序!\n");

exit(0);

}

int len;//表示要创建的节点数

int val;

printf("请输入要创建的节点数:");

scanf("%d",&len);

for(int i=0;i<len;i++)

{

printf("请输入%d个节点的数据:",i+1);

scanf("%d",&val);

pnew=(struct node *)malloc(sizeof(struct node));

if(NULL==pnew)

{

printf("分配内存失败,终止程序!\n");

exit(0);

}

pnew->data=val;

ptail->pnext=pnew;

pnew->pnext=NULL;

ptail=pnew;

}

return phead;

}

//遍历链表函数

void traverse_list(struct node *phead)

{

struct node *p=phead->pnext;

while(p!=NULL)

{

printf("%d ",p->data);

p=p->pnext;

}

printf("\n");

return ;

}

//判断链表是否为空函数

bool is_empty(struct node *phead)

{

if(phead->pnext!=NULL)

return true;

else

return false;

}

int lenght_list(struct node *phead)

{

struct node *p=phead->pnext;

int len=0;

while(p!=NULL)

{

len++;

p=p->pnext;

}

return len;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  链表
相关文章推荐