#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//【1】节点数据类型
typedef struct node
{
int data;
struct node* pnext;
}NODE,*PNODE;
PNODE creat_list();
void travel_list(PNODE phead);
int main(void)
{
//-------------------【2】框架-----------------------
PNODE phead = (PNODE)malloc(sizeof(NODE));
//【3】创建链表
phead = creat_list();
//【4】在下一个函数里遍历链表
travel_list(phead);
return 0;
}
PNODE creat_list()
{
PNODE phead = (PNODE)malloc(sizeof(NODE));
//-------------------【3.1】创建新节点开始--
//【3.2】定义节点的长度 length
int length = 0;int val = 0;
printf("请输入链表的长度");
scanf("%d",&length);
//【3.3】创建尾结点
PNODE ptail = phead;// (PNODE)malloc(sizeof(NODE))
for (size_t i = 0; i < length; i++)
{
PNODE pnew = (PNODE)malloc(sizeof(NODE));
printf("请输入第%d个节点的值",i+1);
scanf("%d",& val);
//【3.4】数据放到新节点
pnew->data = val;
//【3.5】新节点挂到尾结点
ptail->pnext = pnew;
//【3.6】新节点指向NULL
pnew->pnext = NULL;
//【3.7】尾指针重新指向最后的新节点
ptail = pnew;
}
return phead;
}
void travel_list(PNODE phead)
{
//【4.1】创建一个p指针,始终指向
PNODE p =phead->pnext;
//【4.2】循环遍历
while (NULL != p)
{
printf("%d",p->data);
p = p->pnext;
printf("\n");
}
}