栈的基本实现

本文介绍了一个简单的程序,该程序使用栈数据结构将十进制数转换为二进制数。通过逐步输入和输出操作演示了转换过程,并展示了如何动态调整栈大小以适应不同的输入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<malloc.h>
using namespace std;

const stackSize = 10;
const stackIncrement = 5;

typedef struct{
	int *base;
	int *top;
	int stackSize;
} SqStack;

int InitStack(SqStack &s){
	s.base = (int*)malloc( stackSize*sizeof(int) );
	if(!s.base)
		return 0;
	s.top = s.base;
	s.stackSize = stackSize;
	return 1;
}

int Push(SqStack &s, int e){
	if(s.top - s.base >= s.stackSize){
		s.base = (int*)realloc(s.base, (s.stackSize + stackIncrement)*sizeof(int) );

		if(!s.base)
			return 0;
		s.top = s.base + s.stackSize;
		s.stackSize += stackIncrement;
	}
	*s.top++ = e;
	return 1;
}

int Pop(SqStack &s, int &e){
	if(s.top == s.base)
		return 0;
	e = *(--s.top);
	return 0;
}

int StackEmpty(SqStack s){
	if(s.top == s.base)
		return 0;
	return 1;
}
int StackLenth(SqStack s){
	return (s.top - s.base);
}
int main(){
	int decimal;
	cout<<"请输入一个十进制的数: ";
	cin>>decimal;
	SqStack stack;
	InitStack(stack);
	while(decimal){
		Push(stack, decimal % 2);
		decimal /= 2;
	}
	cout<<StackLenth(stack)<<"此数转换为二进制后为:"<<endl;
	int e = 0;
	while( StackEmpty(stack) != 0 ){
		Pop(stack, e);
		cout<<e;
	}
	cout<<endl;
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值