数据结构(七) 顺序栈实现数制转换

来源:互联网 发布:淘宝黑搜二期 编辑:程序博客网 时间:2024/06/05 07:34
//用栈处理数制的转换
//采用的存储结构为顺序存储结构 
#include <iostream>
 
using namespace std;
#define MAXSIZE 100 
//栈的结构体
struct Node
{
int *base;
int *top;
int stackSize;
}; 
//初始化栈的操作
 void initStack(struct Node &S)
 {
  S.base = new int [MAXSIZE];
  if(S.base == NULL)
  {
  cout<<"地址分配失败\n";
  exit(1);
  }
  S.top = S.base;
  S.stackSize = MAXSIZE;
 }
 //入栈操作
void push(struct Node &S,int e)
{
if(S.top-S.base == S.stackSize)
{
cout<<"此栈已经满了\n";
exit(1);
}
*S.top++ = e;

//出栈操作
void pop(struct Node &S,int &e)
{
if(S.top==S.base)
{
cout<<"栈为空\n";
exit(1);
}
e = *--S.top;

void function(struct Node S,int n)
{
int s;
while(n)
{
push(S,n%2);
n = n/2;
}
while(S.top!=S.base)
{
pop(S,s);
cout<<s<<" ";
}
}
 int main()
 {
  struct Node S;
initStack(S);
int n;
cout<<"输入你要转换的十进制数\n";
cin>>n;
function(S,n);
  return 0;
 }
0 0