此例為十進制N轉換為其它進制
1.順序棧的存儲結構

typedef struct{ ElemType data[MAXSIZE];//為順序棧分配最大容量的內存 int top; //指向棧頂 }SqStack;
2.初始化棧

void Initstack(SqStack &S) { if(!S.data) exit(-1); S.top = 0; }
3.入棧

Status Push(SqStack &S,ElemType e) { if(S.top==MAXSIZE) return ERROR; S.data[S.top++] = e; return OK; }
4.出棧

Status Pop(SqStack &S) { if(S.top<=0) return ERROR; S.top--; return OK; }
5.獲得棧頂元素

void getTop(SqStack S,ElemType &e) { if(S.top==0) printf("棧空了!!"); e = S.data[S.top-1]; }
6.進制轉換

void Convertion(SqStack &S) { int n,r; printf("輸入要轉換進制的數:\n"); scanf("%d",&n); printf("輸入要轉換的進制:\n"); scanf("%d",&r); while(n) { Push(S,n%r); n/=r; } while(S.top) { ElemType e; getTop(S,e); Pop(S); printf("%d",e); } printf("\n"); }
7.遍歷

void traverse(SqStack S) { printf("進制轉換結果:\n"); for(int i=S.top-1;i>=0;i--) { printf("%d",S.data[i]); } printf("\n"); }
8.全部代碼(這里就整合為一個了)

#include<stdio.h> #include<stdlib.h> #define MAXSIZE 100 #define ERROR 0 #define OK 1 typedef int Status; typedef int ElemType; typedef struct{ ElemType data[MAXSIZE];//為順序棧分配最大容量的內存 int top; //指向棧頂 }SqStack; void Initstack(SqStack &S) { if(!S.data) exit(-1); S.top = 0; } Status Push(SqStack &S,ElemType e) { if(S.top==MAXSIZE) return ERROR; S.data[S.top++] = e; return OK; } Status Pop(SqStack &S) { if(S.top<=0) return ERROR; S.top--; return OK; } void getTop(SqStack S,ElemType &e) { if(S.top==0) printf("棧空了!!"); e = S.data[S.top-1]; } void Convertion(SqStack &S) { int n,r; printf("輸入要轉換進制的數:\n"); scanf("%d",&n); printf("輸入要轉換的進制:\n"); scanf("%d",&r); while(n) { Push(S,n%r); n/=r; } while(S.top) { ElemType e; getTop(S,e); Pop(S); printf("%d",e); } printf("\n"); } void traverse(SqStack S) { printf("進制轉換結果:\n"); for(int i=S.top-1;i>=0;i--) { printf("%d",S.data[i]); } printf("\n"); } int main() { SqStack S; Initstack(S); Convertion(S); //我看了幾個博客,都是用上面的方法,下面這個也可以 //traverse(S);//這兩個函數只能用一個 return 0; }