任务描述
本小节需要你统计单链表中的节点数。
相关知识
根据上一关我们知道怎么创建单链表了,那么这一关让我们巩固一下单链表的知识。
编程要求
请仔细阅读右侧代码,根据方法内的提示,在Begin - End区域内进行代码补充,具体任务如下:
编写程序,从键盘输入一串整数以及整数的个数,以单链表形式存储起来,计算单链表中结点的个数,输出单链表的数据及结点的个数。
效果如下:
输入:
8
12367802
输出:
12367802
8
代码如下
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct node {
int data;
struct node *next;
}Node;
Node * CreatList()//创建表头
{
Node *phead = (Node *)malloc(sizeof(Node));
phead->next=NULL;
return phead;
}
Node * CreatNode(Node * phead)//创建节点
{
int n;
scanf("%d",&n);
while(n--){
Node * newPoint = (Node *)malloc(sizeof(Node));//创建一个新节点
if(newPoint == 0)
{
printf("内存分配错误\n");
break;
}
scanf("%d", &newPoint->data);
phead->next = newPoint;
phead = newPoint;
}
phead -> next = NULL;
return 0;
}
void ShowList(struct node * headNode)//打印链表
{
struct node * pMove = headNode->next;
while(pMove)
{
printf("%d ",pMove->data);
pMove=pMove->next;
}
}
int Length(Node * phead)//统计节点个数
{
int i=0;
struct node * pMove = phead->next;
while(pMove)
{
i++;
pMove=pMove->next;
}
return i;//返回节点个数
}
int main(void)
{
Node *phead;
phead = CreatList();
CreatNode(phead);
ShowList(phead);
printf("\n%d", Length(phead));
return 0;
}