数组写法:
- #include<stdio.h>
- #define MAX_LEN 100
- typedef int Elemtype;
- typedef struct {
- Elemtype data[MAX_LEN];
- int StackSize;
- }SqStack;
- int InitStack(SqStack* S)
- {
- S->StackSize = -1;
- return 1;
- }
- int PushStack(SqStack* S, Elemtype e)
- {
- S->data[++S->StackSize] = e;
- return 1;
- }
- int StackEmpty(SqStack* S)
- {
- return S->StackSize == -1 ? 1 : 0;
- }
- int PopStack(SqStack* S, Elemtype* e)
- {
- *e = S->data[S->StackSize--];
- return 1;
- }
- void TrsNum(int number, int cet)
- {
- SqStack S;
- Elemtype e;
- InitStack(&S);
- number == 0 ? PushStack(&S, 0) : NULL;
- while (number)
- {
- PushStack(&S, number % cet);
- number = number / cet;
- }
- while (!StackEmpty(&S))
- {
- PopStack(&S, &e);
- switch (e)
- {
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- e += 55;
- break;
- default:
- e += 48;
- }
- printf("%c", e);
- }
- printf("\n");
- }
- int main()
- {
- int number;
- printf("十进制数:");
- scanf("%d", &number);
- TrsNum(number, 2);
- TrsNum(number, 8);
- TrsNum(number, 16);
- return 0;
- }
动态栈写法:
- #include<stdio.h>
- #include<stdlib.h>
- #define INITSIZE 100
- #define INCREMENT 10
- typedef int Elemtype;
- typedef struct {
- Elemtype* base;
- Elemtype* top;
- int StackSize;
- }SqStack;
- int InitStack(SqStack* S)
- {
- S->base = (Elemtype*)malloc(sizeof(Elemtype) * INITSIZE);
- if (!S->base)
- return 0;
- S->top = S->base;
- S->StackSize = INITSIZE;
- return 1;
- }
- int PushStack(SqStack* S, Elemtype e)
- {
- if (S->top - S->base >= S->StackSize)
- {
- S->base = (Elemtype*)realloc(S->base, (S->StackSize + INCREMENT) * sizeof(Elemtype));
- if (!S->base)
- return 0;
- S->top = S->base + S->StackSize;
- S->StackSize += INCREMENT;
- }
- *S->top++ = e;
- return 1;
- }
- int StackEmpty(SqStack* S)
- {
- return S->top == S->base;
- }
- int PopStack(SqStack* S, Elemtype* e)
- {
- if (S->top == S->base)
- return 0;
- *e = *--S->top;
- return 1;
- }
- void TrsNum(int number, int cet)
- {
- SqStack S;
- Elemtype e;
- InitStack(&S);
- number == 0 ? PushStack(&S, 0) : NULL;
- while (number)
- {
- PushStack(&S, number % cet);
- number = number / cet;
- }
- while (!StackEmpty(&S))
- {
- PopStack(&S, &e);
- switch (e)
- {
- case 10:
- case 11:
- case 12:
- case 13:
- case 14:
- case 15:
- e += 55;
- break;
- default:
- e += 48;
- }
- printf("%c", e);
- }
- printf("\n");
- }
- int main()
- {
- int number;
- printf("十进制数:");
- scanf("%d", &number);
- TrsNum(number, 2);
- TrsNum(number, 8);
- TrsNum(number, 16);
- return 0;
- }