目录
1、seqstack.h
#ifndef __SEQSTACK_H__
#define __SEQSTACK_H__
#define MAX 10
typedef int datatype;
typedef struct
{
datatype data[MAX];
int top; //栈顶元素下标
}seqStack;
//创建
seqStack *create();
//判空
int empty(seqStack *S);
//判满
int full(seqStack *S);
//入栈(进栈/压栈)
int push(seqStack *S,datatype e);
//出栈(弹栈)
int pop(seqStack *S);
#endif
2、seqstack.c
#include<stdio.h>
#include<stdlib.h>
#include"seqstack.h"
#include<string.h>
//创建
seqStack *create()
{
seqStack *S = (seqStack *)malloc(sizeof(seqStack));
if(S == NULL)
{
printf("创建失败\n");
return NULL;
}
//初始化
S->top = -1;
printf("创建成功\n");
return S;
}
//判空
int empty(seqStack *S)
{
return S->top == -1? 1:0; //1表示空,0表示非空
}
//判满
int full(seqStack *S)
{
return S->top == MAX-1? 1:0; //1表示满,0表示不满
}
//入栈(进栈/压栈)
int push(seqStack *S,datatype e)
{
//判断逻辑
if(S == NULL || full(S))
{
printf("入栈失败\n");
return -1;
}
//入栈操作
S->top++;
S->data[S->top] = e;
return 0;
}
//出栈(弹栈)
int pop(seqStack *S)
{
if(S ==NULL || empty(S))
{
printf("出栈失败\n");
return -1;
}
//出栈逻辑
printf("%d\t",S->data[S->top]);
S->top--;
return 0;
}
//进制转换函数
void base_change(seqStack *S,int num,int base)
{
if(base <= 10)
{
while(num)
{
int n;
n=num%base;
num=num/base;
push(S,n);
}
while(S->top != -1)
{
pop(S);
}
putchar(10);
}else if(base == 16)
{
while(num)
{
int n2;
n2=num%base;
num=num/base;
S->top++;
S->data[S->top] = n2;
}
while(S->top != -1)
{
if(S->data[S->top] >= 10)
{
switch(S->data[S->top])
{
case 10: printf("A\t"); break;
case 11: printf("B\t"); break;
case 12: printf("C\t"); break;
case 13: printf("D\t"); break;
case 14: printf("E\t"); break;
case 15: printf("F\t"); break;
}
S->top--;
}else{
printf("%c\t",S->data[S->top]);
S->top--;
}
}
putchar(10);
}
}
3、main.c
#include<stdio.h>
#include<stdlib.h>
#include"seqstack.h"
int main(int argc, const char *argv[])
{
//创建
seqStack *S = create();
if(S == NULL)
{
return -1;
}
base_change(S,100,8);
base_change(S,254,16);
return 0;
}