您的位置:首页 > 理论基础 > 数据结构算法

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

2016-12-30 21:34 197 查看
//用栈处理数制的转换

//采用的存储结构为顺序存储结构 

#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;

 }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: