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

计算单链表的长度 计算单链表的长度,实现单链表的打印
实现单链表的建立
链表节点的定义:
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 ");
return;
}
p=head->next;
while(p!=NULL)
{
printf("the %dth node is:%d ",++index,p->data);
p=p->next;
}
}
原文地址:https://www.cnblogs.com/zhangaihua/p/3718075.html