1:利用栈将输入数字倒序输出:
#include <stdio.h> #define STACKSIZE 100 #define OK 1 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType data[STACKSIZE]; int top; }SeqStack; void InitStack(SeqStack *s) { (*s).top = 0; } int StackFull(SeqStack s) { if(s.top == STACKSIZE) return TRUE; else return FALSE; } Status Push(SeqStack *s,ElemType e) { if(StackFull(*s)) return OVERFLOW; (*s).data[(*s).top] = e; (*s).top++; return OK; } int StackEmpty(SeqStack s) { if(s.top == 0) return TRUE; else return FALSE; } Status Pop(SeqStack *s) { if(StackEmpty(*s)) return OVERFLOW; (*s).top--; return OK; } Status GetTop(SeqStack s,ElemType *e) { if(StackEmpty(s)) return OVERFLOW; *e = s.data[s.top-1]; return OK; } Status PopwithTop(SeqStack *s,ElemType *e) { if( StackEmpty(*s) ) return OVERFLOW; *e = (*s).data[(*s).top-1]; (*s).top--; return OK; } int main() { SeqStack s; int n,i; ElemType e; InitStack(&s); printf("输入n:"); scanf("%d",&n); if(n>=0 && n<=STACKSIZE) { printf("输入%d个数:",n); for(i=1;i<=n;i++) { scanf("%d",&e); Push(&s,e); } printf("逆序输出结果:"); while(!StackEmpty(s)) { PopwithTop(&s,&e); printf("%d ",e); } printf("\n"); return OK; } else { printf("输入值不合法!\n"); return OVERFLOW; } }
2:利用栈对数字进行进制转换:
#include <stdio.h> #define STACKSIZE 100 #define OK 1 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 typedef int ElemType; typedef int Status; typedef struct { ElemType data[STACKSIZE]; int top; }SeqStack; void InitStack(SeqStack *s) { (*s).top = 0; } Status StackFull(SeqStack &s) { if(s.top == STACKSIZE) return TRUE; return FALSE; } Status Push(SeqStack *s,ElemType e) { if(StackFull(*s)) return OVERFLOW; (*s).data[(*s).top] = e; (*s).top++; return OK; } int StackEmpty(SeqStack s) { if(s.top == 0) return TRUE; else return FALSE; } Status PopwithTop(SeqStack *s,ElemType *e) { if( StackEmpty(*s) ) return OVERFLOW; *e = (*s).data[(*s).top-1]; (*s).top--; return OK; } int main() { SeqStack s; int n, r; ElemType e; InitStack(&s); printf("请输入数字n和需要转换的进制R:"); scanf("%d %d", &n, &r); printf("把%d转换成%d进制的结果是:", n, r); while(n) { Push(&s, n%r); n /= r; } while(!StackEmpty(s)) { PopwithTop(&s, &e); printf("%c", e>=10?e-10+‘a‘:e+‘0‘); } printf("\n"); return 0; }
时间: 2024-12-30 01:12:54