Java教程

数据结构与算法实验--栈(1)

本文主要是介绍数据结构与算法实验--栈(1),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

        利用顺序栈或链栈,将一个十进制数n转换为d进制数(d=2~16)并应用,计算十进制487的二进制数、八进制数和十六进制分别是多少?

提示:将十进制数转换为d进制数,可以采用除d取余法。

typedef struct {
	string items[STACKSIZE];
	int top;
}SqStack;
int Push(SqStack* S, string e)  //入栈
{
	if (S->top >= STACKSIZE - 1) {
		printf("堆栈已满,不能完成入栈操作!\n");
		return 0;
	}
	S->top++;
	S->items[S->top] = e;
	return 0;
}
int Pop(SqStack* S, string &e)  //出栈
{
	if (S->top <= -1) {
		printf("堆栈已空,不能完成出栈操作!\n");
		return 0;
	}
	e = S->items[S->top];
	S->top--;
	return 0;
}
int trans(int num, int d, SqStack* S)  //转换
{
	int a;
	string b;
	do 
	{
		a = num % d;   //d进制,除d取余法
		num = (num - a) / d;
		switch (a)     //将余数转换为0,1,…,A,B,C…,将其入栈
		{
		case 0:
			Push(S, "0");
			break;
		case 1:
			Push(S, "1");
			break;
		case 2:
			Push(S, "2");
			break;
		case 3:
			Push(S, "3");
			break;
		case 4:
			Push(S, "4");
			break;
		case 5:
			Push(S, "5");
			break;
		case 6:
			Push(S, "6");
			break;
		case 7:
			Push(S, "7");
			break;
		case 8:
			Push(S, "8");
			break;
		case 9:
			Push(S, "9");
			break;
		case 10:
			Push(S, "A");
			break;
		case 11:
			Push(S, "B");
			break;
		case 12:
			Push(S, "C");
			break;
		case 13:
			Push(S, "D");
			break;
		case 14:
			Push(S, "E");
			break;
		case 15:
			Push(S, "F");
			break;
		}
		
	} while (num != 0);
	while (S->top != -1)   //完成后出栈
	{
		Pop(S, b);
		cout << b << " ";
	}
	return 0;
}
int main()
{
	SqStack shun;
	SqStack* S=&shun;
	S->top = -1;
	cout << "输入十进制数" << endl;
	int num;
	cin>>num;
	cout << "输入转化的进制数" << endl;
	int d;
	cin >> d;
	trans(num, d, S);
	return 0;
}

运行结果:

这篇关于数据结构与算法实验--栈(1)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!