#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node *pNext;
}Node;
Node *create_list()
{
int i;
int num;
int val;
Node *phead = (Node *)malloc(sizeof(char));
if(phead == NULL)
{
printf("分配內存失敗,程序終止!\n");
exit(-1);
}
Node *ptail = phead;
phead->pNext = NULL;
printf("請輸入你想創建的節點個數:\n");
scanf("%d",&num);
for(i = 0;i < num;i++)
{
printf("請輸入第%d個節點的值:\n",i + 1);
scanf("%d",&val);
Node *pnew = (Node *)malloc(sizeof(Node));
if(pnew == NULL)
{
printf("分配內存失敗,程序終止\n");
exit(-1);
}
pnew->data = val;
ptail->pNext = pnew;
pnew->pNext = NULL;
ptail = pnew;
}
return phead;
}
void traverse_list(Node *phead)
{
Node *ptr = phead;
if(ptr->pNext == NULL)
{
printf("該鏈表爲空!\n");
return ;
}
while (ptr->pNext != NULL)
{
printf("%d\t",ptr->pNext->data);
ptr = ptr->pNext;
}
printf("\n");
}
int main()
{
Node *phead = NULL;
phead = create_list();
traverse_list(phead);
return 0;
}