#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
struct node
{
int data;
struct node *pnext;
};
struct node *creat_list();
void traverse_list(struct node *phead);
int main()
{
struct node *phead;
phead=creat_list();
traverse_list(phead);
return 0;
}
//建立鏈表函數
struct node *creat_list()
{
struct node *phead,*ptail,*pnew;
phead=(struct node *)malloc(sizeof(struct node));
ptail=phead;
ptail->pnext=NULL;
if(NULL==phead)
{
printf("分配內存失敗,終止程序!\n");
exit(0);
}
int len;//表示要建立的節點數
int val;
printf("請輸入要建立的節點數:");
scanf("%d",&len);
for(int i=0;i<len;i++)
{
printf("請輸入%d個節點的數據:",i+1);
scanf("%d",&val);
pnew=(struct node *)malloc(sizeof(struct node));
if(NULL==pnew)
{
printf("分配內存失敗,終止程序!\n");
exit(0);
}
pnew->data=val;
ptail->pnext=pnew;
pnew->pnext=NULL;
ptail=pnew;
}
return phead;
}
//遍歷鏈表函數
void traverse_list(struct node *phead)
{
struct node *p=phead->pnext;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->pnext;
}
printf("\n");
return ;
}