#include <stdio.h> #include <stdlib.h> #include"PublicDS.h" typedef int ElemType; //定义栈节点的结构 typedef struct StackNode{ ElemType data; struct StackNode* next; }StackNode; //定义栈的结构 typedef struct Stack{ StackNode* top; int count; }Stack; /* * 初始化一个空栈 */ void InitStack(Stack* &s); /* * 销毁栈 */ void DestroyStack(Stack* &s); /* * 清空栈 */ void ClearStack(Stack* s); /* * 判断栈是否为空 */ bool StackEmpty(Stack s); /* * 获取栈的长度 */ int StackLength(Stack s); /* * 获取栈顶元素 */ void GetTop(Stack s, ElemType* e); /* * 将元素压入栈 */ void Push(Stack* &s, ElemType e); /* * 将元素弹出栈 */ void Pop(Stack* &s, ElemType* e); /* * 打印栈 */ void PrintStack(Stack* s,FILE* fout); void InitStack(Stack* &s) { MALLOC(s, sizeof(Stack), Stack*); s->top = NULL; s->count = 0; } void DestroyStack(Stack* &s) { StackNode* sn_tmp_ptr; while (s->top){ sn_tmp_ptr = s->top; s->top = s->top->next; free(sn_tmp_ptr); } free(s); } void ClearStack(Stack* &s) { while (s->top){ s->top->data = 0; s->top = s->top->next; } } bool StackEmpty(Stack s) { return s.count<1 ; } int StackLength(Stack s) { return s.count; } void GetTop(Stack s, ElemType* e) { *e = s.top->data; } void Push(Stack* &s, ElemType e) { StackNode* snptr; MALLOC(snptr, sizeof(StackNode), StackNode*); snptr->data = e; snptr->next = s->top; s->top = snptr; s->count++; } void Pop(Stack* &s, ElemType* e) { *e = s->top->data; StackNode* sn_tmp_ptr = s->top; s->top = s->top->next; s->count--; free(sn_tmp_ptr); } void PrintStack(Stack* s,FILE *fout) { while (s->top){ fprintf(fout,"%d", s->top->data); s->top = s->top->next; } } void main(){ FILE *fin, *fout; fin = fopen("input.txt", "r"); fout = fopen("output.txt", "w"); int tmp = 0; while (!feof(fin)){ fscanf(fin, "%d", &tmp); if (tmp != -1){ fprintf(fout, "%8d--->", tmp); Stack *sc = NULL; InitStack(sc); while (tmp / 2 != 0) { Push(sc, tmp % 2); tmp /= 2; } Push(sc, tmp); PrintStack(sc, fout); fprintf(fout, "\n"); DestroyStack(sc); } } fclose(fin); fclose(fout); system("pause"); }
时间: 2024-10-11 18:05:37