【資料結構 C描述】使用順序棧編制一個滿足下列要求的程式:對於輸入的任意一個非負十進位制數,列印輸出與其等值的二進位制數。
阿新 • • 發佈:2018-12-26
【資料結構 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]);
}
}
執行截圖: