//栈的顺序存储
//stack.h
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
typedef int ElemType;
typedef struct //SqStack
{ElemType a[MAXSIZE];
int top;
}SqStack;
void init_s(SqStack *s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
/******************************检测完毕*****************************/
void out_s(SqStack *s)//print the elems of the stack
{
int i;
if(s->top==-1) printf("\n Stack is NULL");
else{ i=s->top;
while(i!=-1)
{printf("\n data[%d]=%d", i,s->a[i]);i--;}
}
}
/****************************检测完毕*******************************/
void push(SqStack *s,ElemType e)
{
if(s->top==MAXSIZE-1)printf("\n Stack is overflow!");
else{s->top++;
s->a[s->top]=e;
}
}
/*********************检测完毕**************************************/
ElemType pop(SqStack *s)
{
ElemType x;
if(s->top==-1) {printf("\n Stack is NULL");x=-1;}
else{x=s->a[s->top];s->top--;}
return x;
}
测试程序main
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"
#define MAXSIZE 20
typedef int ElemType;
SqStack s1,s2;
void conversion(int M,int N);
void main()
{
int k,a,b;ElemType x,y;char ch;
init_s(&s2);
do{
printf("\t\t============================\n");
printf("\t\t==1、进栈 ==\n");
printf("\t\t==2、出栈 ==\n");
printf("\t\t==3、输出栈 ==\n");
printf("\t\t==4、进制转换 ==\n");
printf("\t\t==5、结束 ==\n");
printf("\t\t============================\n");
scanf("%d",&k);
switch(k)
{
case 1:{//ElemType y;
printf("输入进栈元素:");
scanf("%d",&y);
push(&s2,y);
printf("进栈元素是:%d\n",y);
break;
}
case 2:{x=pop(&s2);
printf("出栈元素是:%d\n",x);
break;
}
case 3:{out_s(&s2);
printf("\n");
break;
}
case 4:{printf("要进行进制转换的数是:");scanf("%d",&a);
printf("转换成n进制,n=");scanf("%d",&b);
conversion(a,b);
break;
}
}
//printf("\n\n\t\t==按任意键返回主菜单==\n\t\t");
//fflush(stdin);
//scanf("%c",&ch);
}while(k!=5);
}
void conversion(int M,int N)
{
ElemType c;
init_s(&s1);
while(M!=0)
{
push(&s1,M%N);
M=M/N;
}
printf("\n转换后的数字是:");
while(s1.top!=0)
{
c=pop(&s1);
printf("%d",c);
//out_s(&s1);
}
printf("\n");
}