文章目录
- 一、入栈、出栈操作
- 二、利用栈操作将十进制的数转化为二进制
一、入栈、出栈操作
#include<iostream>
using namespace std;
#define MAXSIZE 10
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
bool CreateStack(SqStack &S)
{
S.base= new SElemType[MAXSIZE];
if(!S.base) return(0);
S.top= S.base;
S.stacksize= MAXSIZE;
return(1);
}
bool Push(SqStack &S, SElemType e)
{
if(S.top-S.base==S.stacksize) return(0);
*S.top++=e;
return(1);
}
bool Pop(SqStack &S, SElemType e)
{
if(S.top==S.base) return(0);
e= *--S.top;
return(1);
}
SElemType GetTop(SqStack &S)
{
if(S.top != S.base)
return *(S.top-1);
}
int main()
{
SElemType E;
SqStack s;
CreateStack(s);
Push(s, 77);
Push(s, 88);
Push(s, 99);
cout << "入栈后栈顶:" << GetTop(s) << endl;
Pop(s, E);
cout << "出栈后栈顶:" << GetTop(s) << endl;
}
二、利用栈操作将十进制的数转化为二进制
#include<iostream>
using namespace std;
#define MAXSIZE 10
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
bool CreateStack(SqStack &S)
{
S.base= new SElemType[MAXSIZE];
if(!S.base) return(0);
S.top= S.base;
S.stacksize= MAXSIZE;
return(1);
}
bool Push(SqStack &S, SElemType e)
{
if(S.top-S.base==S.stacksize) return(0);
*S.top++=e;
return(1);
}
bool Pop(SqStack &S, SElemType e)
{
if(S.top==S.base) return(0);
e= *--S.top;
return(1);
}
SElemType GetTop(SqStack &S)
{
if(S.top != S.base)
return *(S.top-1);
}
int main()
{
int N, r=2, j;
SElemType E;
SqStack s;
CreateStack(s);
cout << "请输入要转换的数据:" << endl;
cin >> N;
while(N!=0)
{
j=N%r;
Push(s,j);
N=N/r;
}
while(s.top != s.base)
{
cout << GetTop(s);
Pop(s, E);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)