#include<stdio.h>
#include<windows.h>
#include<malloc.h>
//構(gòu)造順序棧的數(shù)據(jù)類型
#define MaxSize 50
typedef char ElemType;
struct stack
{
char data[50]; ?//保存數(shù)據(jù)元素
int Top;? ? ?????? //棧頂指針(虛指針)
};
typedef struct stack SqStack;
/*
函數(shù)功能:向系統(tǒng)申請(qǐng)空間存儲(chǔ)順序棧,且為空棧
函數(shù)形參:SqStack *S
函數(shù)返回值:無
*/
void InitStack(SqStack *&s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->Top=-1;? ? ? //空棧的標(biāo)志
}
/*
函數(shù)功能:Push
函數(shù)形參:S(棧),e(入棧元素)
函數(shù)返回值:棧滿 返回0 否則 入棧返回1
*/
int Push(SqStack *s,ElemType e)
{
//判斷棧滿
if(s->Top==MaxSize-1)? return 0;
//入棧
s->Top++;
s->data[s->Top]=e;
return 1;
}
/*
函數(shù)功能:GetTop
函數(shù)形參:s,&e(取棧頂元素)
函數(shù)返回值:空棧返回0,否則返回1,e中存棧頂元素
*/
int GetTop(SqStack *s,ElemType &e)
{
//判斷棧是否空棧
if(s->Top==1) return 0;
e=s->data[s->Top];
return 1;
}
/*
函數(shù)功能:Pop
函數(shù)形參:是,&e(取棧頂元素,類似回收站的作用)
函數(shù)返回值:空棧返回0,否則元素出棧返回1
*/
int Pop(SqStack *s,ElemType &e)
{
if(s->Top==-1) return 0;
//將刪除元素存入回收站e
e=s->data[s->Top];
//移動(dòng)棧指針
s->Top--;
return 1;
}
int main()
{
SqStack *s;
ElemType e;
int n,r,t;
printf("(1)初始化空棧\n");InitStack(s);
//用戶輸入轉(zhuǎn)換的十進(jìn)制數(shù)n是?轉(zhuǎn)換成幾進(jìn)制r?
scanf("%d %d",&n,&r);
while(n!=0)
{
t=n/r;
e=n%r;
//取余數(shù)
Push(s,e);
//對(duì)被除數(shù)迭代
n=t;
}
if(GetTop(s,e)==1) printf("(3)當(dāng)前棧頂元素是%d\n",e);
else? ? ? ? ? ? ? printf("(3)當(dāng)前為空棧\n");
while (s->Top!=-1)
{
if(Pop(s,e)==1) printf("%d",e);
else? ? ? ? ? ? printf("(4)當(dāng)前為空棧\n");
}
system("PAUSE");
return 0;
}