首页 > 学院 > 开发设计 > 正文

C实例---进制转换(栈实现)

2019-11-10 20:00:13
字体:
来源:转载
供稿:网友

代码:

#include <stdio.h>#include <string.h>#include <stdlib.h>#define STACKSIZE 100typedef int ElemType;enum {a = 10, b,c,d,e,f};typedef struct stack{ ElemType *base; ElemType *top;}SeqStack;void InitialStack(SeqStack *Stack){ if ((Stack->base = (ElemType *)malloc(STACKSIZE * sizeof(ElemType))) == NULL) { PRintf("Line %d : Stack malloc error!/n",__LINE__); exit(1); } Stack->top = Stack->base;}int IsEmpty(SeqStack *Stack){ if (Stack->top== Stack->base) return 1; else return 0;}int IsFull(SeqStack *Stack){ if ((Stack->top - Stack->base) == (STACKSIZE - 1)) return 1; else return 0;}void Push(SeqStack *Stack, ElemType data){ if (IsFull(Stack)) { printf("Line %d : Stack Overflow!/n",__LINE__); exit(2); } *(Stack->top ++) = data;}ElemType Pop(SeqStack *Stack){ if (IsEmpty(Stack)) { printf("Line %d : Stack overflow!/n",__LINE__); exit(3); } return *--Stack->top;}ElemType Top (SeqStack *Stack){ if (IsEmpty(Stack)) { printf("Line %d : Stack overflow!/n",__LINE__); exit(4); } return *(Stack->top -1);}void Conversion(SeqStack *Stack, int N, int B){ int i; InitialStack(Stack); while (N) { Push(Stack, N % B); N = N / B; } while (!IsEmpty(Stack)) { i = Pop(Stack); printf("%d",i); } printf("/n");}int main(){ SeqStack *Stack; printf("十进制 : 10/n"); printf("二进制 : "); Conversion(Stack, 10, 2); return 0;}

运行结果: 这里写图片描述


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表