您的位置:首页 > 其它

计算带头结点单链表的长度 计算单链表的长度,实现单链表的打印

2014-05-08 20:39 381 查看
计算单链表的长度 计算单链表的长度,实现单链表的打印

实现单链表的建立

链表节点的定义:
typedef struct node
{
int data;//节点内容
node *next;//下一个节点
}
创建单链表
node *Create()
{
int i=0;//链表中数据个数
node *head,*p,*q;
int x=0;
head=(node*)malloc(sizeof(node));//创建头结点
while(1)
{
printf("input the data:");
scanf("%d",&x);
if(x==0)

break;//Data为0时创建结束
p=(node*)malloc(sizeof(node));
p->data=x;
if(++i==1)
{
head->next=p;//连接到head的后面
}
else
{
q->next=p;//连接到链表尾端
}
q=p;
q->next=NULL;//链表的最后一个指针为NULL
return head;
}
}

编程实现单链表的测长:
返回单链表的长度
int length(node *head)
{
int len=0;
node *p;
p=head->next;
while(p!=NULL)
{
len++;
p=p->next;
}
return len;
}
实现单链表的打印
void print(node *head)
{
node *p;
int index=0;
if(head->next==NULL)//链表为空
{
printf("link is empty\n");
return;
}
p=head->next;
while(p!=NULL)
{
printf("the %dth node is:%d\n",++index,p->data);
p=p->next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐