链表的创建与链表的遍历
代码描述
# include<stdio.h>
# include<malloc.h>
# include<stdlib.h>
typedef struct Node // 定义链表每一个节点的类型
{
int data; // 数据域
struct Node * pNext; // 指针域
}NODE, *PNODE; // NODE相当于struct Node类型;PNODE相当于struct Node *类型
// 前置函数声明
PNODE creat_list(void);
void traverse_list(PNODE pHead);
int main(void)
{
PNODE pHead = NULL;
pHead = creat_list();
traverse_list(pHead);
return 0;
}
PNODE creat_list(void)
{
int len;
int i;
int val;
printf("请输入链表的长度:len = ");
scanf("%d", &len);
PNODE pHead = (PNODE)malloc(sizeof(NODE)); // 动态分配内存
if(NULL == pHead)
{
printf("内存分配失败,终止程序!\n");
exit(-1);
}
PNODE pTail = pHead;
pTail->pNext = NULL;
for(i = 0; i < len; i++)
{
printf("请输入第%d个节点的数据:", i+1);
scanf("%d", &val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if(NULL == pNew)
{
printf("内存分配失败,终止程序!\n");
exit(-1);
}
pNew->data = val;
pNew->pNext = NULL;
pTail->pNext = pNew;
pTail = pNew;
}
return pHead;
}
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while(NULL != p)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
运行结果