|
楼主 |
发表于 2020-5-7 21:02:02
|
显示全部楼层
本帖最后由 zqdlly 于 2020-5-7 23:21 编辑
源码
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<malloc.h>
#define LEN sizeof(struct general) //general结构的大小
struct general *creatList();//创建链表;
void printList(struct general* head);//打印列表
struct general
{
char* name;
int force;
int intelligence;
struct general *next;//对链表很重要
};
int n;
struct general *creatList()//创建链表;
{
struct general *head;
struct general *p1,*p2;
p1=p2=(struct general *)malloc(LEN);//LEN general结构的大小,这里p1和p2都指向第一个申请的新节点
printf("Enter the name:");
scanf("%s",p1->name);
printf("Enter the force:");
scanf("%d",&p1->force);
printf("Enter the intelligence:");
scanf("%d",&p1->intelligence);
head=NULL;
n=0;//计数器,记录存放个数
while(strcmp(p1->name,"over")!=0 )//当输入0的时候退出循环
{
n++;
if(n==1)//只有第一次有效
{
head=p1;
}
else//
{
p2->next=p1;
}
p2=p1;
p1=(struct general *)malloc(LEN);//p1再申请一个节点
printf("\nEnter the name:");
scanf("%s",p1->name);
printf("Enter the force:");
scanf("%d",&p1->force);
printf("Enter the intelligence:");
scanf("%d",&p1->intelligence);
}
p2->next=NULL;
return head;//返回链表头结点的指针,相当于数组的首地址。链表就是强化版的数组,比如插入等操作,数组很难,链表容易ccccc
};
void printList(struct general* head)
{
struct general* pMove;
pMove = head;
if(head)
{
do
{
printf("name:%s 武力:%d 智力:%d\n", pMove->name, pMove->force, pMove->intelligence);
pMove = pMove->next;
}while(pMove);
}
printf("总人数=%d\n",n);
}
main()
{
struct general *gen;
gen=creatList();
printList(gen);//打印链表需要自定义函数,c没有内置
system("pause");
}
|
|