#include
#include
#include
typedef struct Node //创建新的数据类型
{
int data; //数据域
struct Node * pNext; //指针域
}NODE, *PNODE; //NODE等价与struct Node //PNODE等价于struct Node *
//函数声明
PNODE create_list();
void traverse_list(NODE pHead);
int main()
{
PNODE pHead = NULL;
pHead = create_list(); //create_lsit()功能:创建一个非循环单链表,并将该链表的头结点的地址付给pHead
traverse_list(pHead);
return 0;
}
PNODE create_list()
{
int len; //用来存放有效节点的个数
int i;
int val; //用来临时存放用户输入的结点的值
PNODE pHead = (PNODE)malloc(sizeof(NODE));
pHead->pNext = NULL;
if (NULL == pHead)
{
printf("内存分配失败,程序终止!");
exit(-1);
}
printf("请输入您需要生成的链表节点个数:len = ");
scanf("%d", &len);
for (i=0; i<len; i++)
{
printf("请输入第%d个结点的数据:", i+1);
scanf("%d", &val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pHead)
{
printf("内存分配失败,程序终止!");
exit(-1);
}
pNew->data = val;
pNew->pNext = pHead->pNext;
pHead->pNext = pNew;
}
return pHead;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while(p)
{
printf("%d ", p->data);
p = p->pNext;
}
}