定义结构体
#include//printf #include //malloc #include //strlen #define BUF_MAXLEN 1024 typedef int Elemtype; //数据元素的类型 //数据节点 typedef struct node { Elemtype data; //数据域:保存数据本身用的 struct node *next; //指针域:用来保存关系用的,保存下一个数据节点的地址 }Node; typedef struct head { Elemtype num; //数据域:保存数据本身用的 struct node *first; //头指针 struct node *last; //尾指针 } Head;
Head *Create_Linklist_Head()
{
//先创建一个头结点并且对其初始化
Head *head = malloc(sizeof(Head));
head->first = head->last = NULL;
head->num = 0;
printf("请输入数据:n");
Elemtype d;
while(1)
{
//1.从终端上获取用户输入
scanf("%d",&d);
if(d == 0)
{
break;
}
//2.创建一个数据节点保存获取到的数据
Node *pnew = malloc(sizeof(*pnew));
pnew->data = d;
pnew->next = NULL;
//3.将新节点插入到链表中去
if(head->num == 0)
{
head->first = head->last = pnew;
}
else//尾插法
{
head->last->next = pnew;
head->last = pnew;
}
head->num++;
}
return head;
}
void Print_Linklist_Head(Head *head)
{
Node *p = head->first;
printf("此链表中有%d个节点:n", head->num);
// printf("链表节点地址:%pn头节点的first:%pn尾节点的last:%pn节点数:%dn ", head, head->first,head->last,head->num);
while (p)
{
printf("%d ", p->data);
p = p->next;
}
putchar('n');
}
//请根据用户的输入创建一个带头节点的线性表,以0作为结尾。
//以链式结构(链表)的方式去保存线性表中的数据。
int main()
{
//创建一条带头结点的单链表
Head *head = Create_Linklist_Head();
Print_Linklist_Head(head);
return 0;
}
**运行结果**
大家有什么问题可以私信我哦!



