【数据结构 C描述】使用顺序栈编制一个满足下列要求的程序:对于输入的任意一个非负十进制数,打印输出与其等值的二进制数。

版权声明:AlanLee版权所有 https://blog.csdn.net/qq1445654576/article/details/83217272

【数据结构 C描述】使用顺序栈编制一个满足下列要求的程序:对于输入的任意一个非负十进制数,打印输出与其等值的二进制数。

//main.cpp
#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include "SqStack.h"
using namespace std;

int main()
{
	void conversion();
	conversion();
	system("pause");
	return 0;
}

//十进制转二进制的函数
void conversion() {
	SqStack *S;
	InitStack(S);
	cout << "请输入一个整数:";
	int num = 0;
	int div = 0;
	int mod = 0;
	cin >> num;
	for (int i = 0;num != 0;i++) {
		div = num / 2;		//除一次后剩下的数
		mod = num % 2;		//最终的余数
		Push(S,mod);		//将最终的余数一个一个的压入栈中
		num = div;			//将上一次除后剩下的数赋值给num作为被除数,以继续循环
	} 
	cout << "转换为二进制的数字为:";
	reverseDispStack(S);	//反向输出栈内元素
	cout << endl;
	DestoryStack(S);
}


//SqStack.h
#include <iostream>
#define MaxSize 50
using namespace std;

typedef int ElemType;
typedef struct {
	ElemType a[MaxSize];
	int top;
}SqStack;

void InitStack(SqStack *&S) {
	S = (SqStack *)malloc(sizeof(SqStack));//分配一个顺序栈空间,首地址存放在S中
	S->top = -1;//初始时,栈顶置为-1,即栈为空
}

void DestoryStack(SqStack *&S) {
	free(S);//释放内存空间
}


//反序输出栈元素
void reverseDispStack(SqStack *&S) {
	for (int i = S->top; i >= 0; i--) {
		cout << S->a[i] << " ";
	}
}

bool StackEmpty(SqStack *&S) {
	return (S->top == -1);
}

bool Push(SqStack *&S, ElemType e) {
	if (S->top == MaxSize - 1) {//栈满的情况,即栈上溢出
		return false;
	}
	else {
		S->top++;//栈顶加1
		S->a[S->top] = e;//将元素e放在栈顶
		return true;
	}
}

bool Pop(SqStack *&S, ElemType &e) {//栈空的情况,即栈下溢出
	if (S->top == -1) {
		return false;
	}
	e = S->a[S->top];//将栈顶元素放在e中
	S->top--;//栈顶减1
	return true;
}

bool GetTop(SqStack *&S, ElemType e) {
	if (S->top == -1) {//栈空的情况,即栈下溢出
		return false;
	}
	e = S->a[S->top];//将栈顶元素放在e中
	return true;
}

int StackLength(SqStack *&S) {
	int length = 0;

	//判断栈是否为空
	if (StackEmpty(S)) {
		return length = 0;
	}
	else {
		return length = S->top + 1;
	}
}

void CreateStack(SqStack *&S, ElemType a[], int len) {
	for (int i = 0; i < len; i++) {
		Push(S, a[i]);
	}
}


运行截图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq1445654576/article/details/83217272