64,651
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
typedef struct Lnode //构建结点结构体
{
int data;
struct Lnode* next;
}Lnode;
void Linklist(Lnode** head) //头插法建立链表
{
*head = (Lnode*)malloc(sizeof(Lnode));
(*head)->next = NULL; //头结点
Lnode* p;
//int n=5;
for (int i = 0; i < 5; i++) //生成n个新结点
{
p = (Lnode*)malloc(sizeof(Lnode)); //申请新的空间
printf("input a number:\n");
scanf("%d", &p->data);
p->next = (*head)->next;
(*head)->next = p;
}
}
int Length(Lnode* head) //求链表长度
{
int c = 0;
Lnode* S = head->next; //
while (S != NULL)
{
c++;
S = S->next; //向下一个结点移动
}
return c;
}
void main() //主函数
{
int count;
Lnode* L=NULL;
Linklist(&L);
count = Length(L);
printf("%d\n", count);
}