[C语言、C++]数据结构作业:利用链栈实现数制转换

测试用例: 

 

#include <iostream>
using namespace std;
#define InitSize 100
#define StackIncrement 50
typedef int ElemType;
typedef struct { //顺序栈定义
	ElemType* elem; //栈数组
	int top; //或ElemType*,栈顶指针
	int size; //栈大小
} SeqStack;
int InitStack(SeqStack& S) { //初始化
	S.elem = new ElemType[InitSize];
	if (!S.elem) exit(1);
	S.top = -1;
	S.size = InitSize;
	return 1;
}
int IsEmpty(const SeqStack& S) {
	//判断栈是否空,空则返回1,否则返回0
	return S.top == -1;
}
int IsFull(const SeqStack& S) {
	//判断栈是否,满则返回1,否则返回0
	return S.top == S.size;
}
int Push(SeqStack& S, ElemType e) {
	//若栈满返回0, 否则新元素 e 进栈并返回1
	if (IsFull(S)) return 0;
	S.top++; //先移动指针
	S.elem[S.top] = e; //再加入新元素
	return 1;
}
int Pop(SeqStack& S, ElemType& e) {
	//若栈空返回0, 否则栈顶元素退出到e并返回1
	if (IsEmpty(S)) return 0;
	e = S.elem[S.top]; S.top--;
	return 1;
}
int GetTop(const SeqStack& S, ElemType& e) {
	//若栈空返回0, 否则栈顶元素读到e并返回1
	if (IsEmpty(S)) return 0;
	e = S.elem[S.top];
	return 1;
}
void OverFlow(SeqStack& S) { //栈满处理
	int newSize = S.size + StackIncrement;
	ElemType* newS = new ElemType[newSize];
	if (!newS) exit(1);
	ElemType* src = S.elem,
		* obj = newS;
	for (int i = 0; i < S.size; i++)
		*obj++ = *src++; //向新数组传送数据
	delete[]S.elem; //释放老数组
	S.elem = newS; //新数组作为栈数组
	S.size = newSize; //新数组大小
} //栈顶指针不变
void Traverse(const SeqStack& S) {//遍历栈
	if (IsEmpty(S)) cout << "空表,无法遍历" << endl;
	for (int i = 0; i <= S.top; i++) {
		cout << S.elem[i] << endl;
	}
}
int Clear(SeqStack& S) {//清空栈
	if (IsEmpty(S))return 1;
	S.top = -1;
	return 1;
}
int Destroy(SeqStack& S) {//销毁栈
	free(S.elem);
	S.elem = NULL;
	S.size = 0;
	S.top = NULL;
	return 1;
}
int main() {
	SeqStack S1;
	SeqStack S2;
	InitStack(S1);
	InitStack(S2);
	int n=1348 ,n1 = 1348;
	int m=11 ,m1= 11;
	int d = 8; int b = 2;
	int e;
	while (m) {
		Push(S2, m % b);
		m = m / b;
	}
	printf("(%d)10=(", m1);
	while (!IsEmpty(S2)) {
		Pop(S2, e);
		cout <<e;
	}
	cout << ")2";
	cout << endl;
	while (n) {
		Push(S1, n%d);
		n = n / d;
	}
	printf("(%d)10=(", n1);
	while (!IsEmpty(S1)) {
		Pop(S1, e);
		cout << e;
	}
	cout << ")8";
}
  • 1
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值