单链表逆置
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#define Error(Str) FatalError(Str)
#define FatalError(Str) fprintf(stderr,"%s\n",Str),exit(1) #define MAX 1000
typedef int ElementType;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct Node
{
ElementType Element;
Position Next;
};
void DeleteList( List L )
{
Position P, Tmp;
P = L->Next; /* Header assumed */
L->Next = NULL;
while( P != NULL )
{
Tmp = P->Next;
free( P );
P = Tmp;
}
}
List MakeEmpty( List L )
{
if( L != NULL )
DeleteList( L );
L = malloc( sizeof( struct Node ) );
if( L == NULL )
FatalError( "Out of memory!" );
L->Next = NULL;
return L;
}
List Reverse( List L )
{
Position Old_head, New_head, Temp;
New_head =NULL;
Old_head =L->Next;
while ( Old_head )
{
Temp = Old_head ->Next;
Old_head ->Next = New_head;
New_head = Old_head;
Old_head = Temp;
}
L->Next = New_head;
return L;
}
Position Advance( Position P )
{
return P->Next;
}
void Insert( ElementType X, List L, Position P ) {
Position TmpCell;
TmpCell = malloc( sizeof( struct Node ) ); if( TmpCell == NULL )
FatalError( "Out of space!!!" );
TmpCell->Element = X;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
void PrintList(List L, FILE * fp)
{
if (fp == NULL)
Error("Can't open the output file!\n"); Position p = L->Next;
while (p != NULL)
{
fprintf(fp, "%d", p->Element);
p = p->Next;
if (p != NULL)
fprintf(fp, ",");
}
fprintf(fp, "\n");
}
int main()
{
FILE * fp_input;
FILE * fp_output;
char one_line[MAX];
char * number;
Position tail;
fp_input = fopen("input.txt", "r");
if (fp_input == NULL)
Error("Can't open the input file!\n");
fp_output = fopen("output.txt", "w");
if (fp_output == NULL)
Error("Can't open the output file!\n");
List header = NULL;
while (!feof(fp_input))
{
header = MakeEmpty(header);
tail = header;
fgets(one_line, MAX, fp_input);
number = strtok(one_line, ",");
while (number != NULL)
{
Insert(atoi(number), header, tail); number = strtok(NULL, ",");
tail = Advance(tail);
}
Reverse(header);
PrintList(header, fp_output);
}
MakeEmpty(header);
fclose(fp_output);
fclose(fp_input);
return 0;
}