数据结构-链表C语言实现
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;//数据域
struct Node * pNext;//指针域
}NODE, *PNODE;
PNODE create_list(void){
int len;//用来存放有效节点的个数
int i;//用来临时存放用户输入的节点的值
int val;//节点的值
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if (NULL == pHead) {
printf("分配失败,程序终止!");
exit(-1);
}
printf("请输入您要输入的链表个数");
scanf("%d",&len);
PNODE pTail = pHead;
pTail->pNext = NULL;//pTail永远指向尾节点
for (i=0; i<len; ++i){
printf("请输入第%d个节点的值:",i+1);
scanf("%d",&val);
PNODE pNew = (PNODE)malloc(sizeof(NODE));
if (NULL == pNew)
{
printf("分配失败,程序终止!");
exit(-1);
}
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
void traver_list(PNODE pHead){
PNODE pTmp = pHead;//设置一个临时的节点用于遍历
while (1) {
if (pTmp->pNext == NULL) {
return;
}
printf("%d",pTmp->pNext->data);
pTmp->pNext = pTmp->pNext->pNext;
}
}
int main(int argc, const char * argv[]) {
PNODE pHead = NULL;//等价于 struct Node *pHead = NULL;
pHead = create_list();//创建一个非循环单链表并把首地址付给pHead
traver_list(pHead);//遍历一遍链表
return 0;
}