第1个回答 2011-09-23
楼上写的挺好,有点小问题,帮忙修正一下:
void PrintNode(Node *node) //原函数实现,会丢失最后一个数,在循环外补上
{
while( node->pNext )
{
printf("%d ", node->nData);
node = node->pNext ; //为什么要采用递归调用呢?这样不是很好?
}
printf("%d ", node->nData);//输出最后一个数
}
还有打开文件后,记得在返回(退出)前进行文件关闭:
fclose(fp);
第2个回答 2011-09-23
1.dat
12 36 98 75 4 6 85 107 52
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct _Node
{
int nData;
struct _Node * pNext;
}Node;
void PrintNode(Node *node)
{
if (NULL != node->pNext)
{
printf("%d ", node->nData);
PrintNode(node->pNext);
}
}
int main(void)
{
FILE *fp = NULL;
char a[128] = {0};
char *p = NULL;
Node *head = NULL;
Node *node = NULL;
if((fp=fopen("1.dat","r"))==NULL)
{
printf("文件打开错误");
return -1;
}
fgets(a, sizeof(a), fp);
printf("a=%s\n", a);
head = (Node *)malloc(sizeof(Node));
head->pNext = NULL;
p = strtok(a, " ");
while(NULL != p)
{
node = (Node *)malloc(sizeof(Node));
node->nData = atoi(p);
node->pNext = head->pNext;
head->pNext = node;
p = strtok(NULL, " ");
}
PrintNode(head->pNext);
printf("\n");
return 0;
}本回答被提问者采纳