逆序输入建立链表并从屏幕输出以及写入指定的文件(在线等)
ishe 2003-09-01 04:49:24 我写了这段代码,vc++编译,链接正常,但输出不如人意请高人指点迷津,3~Q:
//整型,屏幕正确输出,不能文件写入
#include <stdio.h>
#include <io.h>
#include <process.h>
#include <iostream.h>
#include <malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
void main()
{
//逆位序输入n个元素的值,建立带表头结点的单链线性表L.
FILE *out;
char outfile[10];
int j;
int i;
LNode *L,*p,*h,*g;
printf("Enter the outfile name:\n");
scanf("%s",outfile);
if((out=fopen(outfile,"w"))==NULL)
{
printf("cannot open outfile\n");
exit(0);
}
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL; //先建立一个带表头结点的单链表
for (i=5;i>0;--i)
{
p=(LinkList)malloc(sizeof(LNode)); //生成新结点
scanf("%d",&p->data); //输入元素值
p->next=L->next;L->next=p; //插入到表头
}
h=L->next; //保存表头
g=L->next;
for(i=1;i<=5;i++)
{
printf("%d\n",h->data);
h=h->next;
}
for(i=1;i<=5;i++)
{
j=g->data;
fputc(j,out);
fputc('\n',out);
g=g->next;
}
fclose(out);
}
=================================================================================+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//字符型,文件,屏幕都不能正确输出??????????????????????????faint
#include <stdio.h>
#include <io.h>
#include <process.h>
#include <iostream.h>
#include <malloc.h>
typedef struct LNode
{
int data;
struct LNode *next;
}LNode,*LinkList;
void main()
{
//逆位序输入n个元素的值,建立带表头结点的单链线性表L.
FILE *out;
char outfile[10];
int j;
int i;
LNode *L,*p,*h,*g;
printf("Enter the outfile name:\n");
//j=getchar();//此语句用来接收在执行scanf语句时最后输入的回车符
scanf("%s",outfile);
if((out=fopen(outfile,"w"))==NULL)
{
printf("cannot open outfile\n");
exit(0);
}
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL; //先建立一个带表头结点的单链表
for (i=5;i>0;--i)
{
p=(LinkList)malloc(sizeof(LNode)); //生成新结点
scanf("%c",&p->data); //输入元素值
p->next=L->next;L->next=p; //插入到表头
}
h=L; //保存表头
g=L;
for(i=1;i<=5;i++)
{
printf("%c\n",L->data);
L=L->next;
}
for(i=1;i<=5;i++)
{
j=g->next->data;
fputc(j,out);
fputc('\n',out);
g=g->next;