C语言实现链表数据顺序输入输出
构建一个链表,用于存放用户输入的数据,一个数据为一个节点,按照输入的先后顺序加到链表中。当用户输入0时结束输入并按输入先后顺序输出数据。
具体实现代码如下:
#include <stdio.h>
#include <stdlib.h>
struct node{
int n;
struct node *pNext;
};
void main(){
struct node *pHead = NULL, *pEnd = NULL, *pNode = NULL;
int i = 1;
printf("Please input a integer:\n");
printf("end by inputing 0:");
do{
scanf("%d",&i);
if(i != 0){
pNode = (struct node *)malloc(sizeof(struct node));
if(pNode != NULL){
pNode -> n = i;
pNode -> pNext = NULL;
if(pHead == NULL){
pHead = pNode;
pEnd = pNode;
}
else{
pEnd -> pNext = pNode;
pEnd = pNode;
}//end of if(pHead == NULL)
}//end of if(pNode != NULL)
}//end of if(i == 0)
}while(i != 0);
pNode = pHead;
while(pNode != NULL){
printf("%d\t", pNode -> n);
pHead = pNode;
pNode = pNode -> pNext;
free(pHead);
}
printf("\n");
}
输出结果如下图所示: