数据结构:输入一个非零正整数,输出其各位数字。要求数字之间间隔至少一个空格。例如:输入12085, 输出为1 2 0 8 5。要求:采用递归和非递归(用堆栈)两种算法;输入

#include<iostream>
using namespace std;
void firstdisplay(int n) {                  //使用递归
	int x = n / 10;
	int y = n % 10;
	if (x >0) {
		firstdisplay(x);
		cout << y << " ";
	}
	else{
		cout << y << " ";
	}
}
struct MyStack {                    //构造栈
	int data;
	MyStack* next;
};
struct LinkStack {
	MyStack* top;
};
void Create(LinkStack &s) {
	s.top = NULL;
}
bool IsEmpty(LinkStack& s) {
	if (s.top == NULL) {
		return true;
	}
	else {
		return false;
	}
}
void Push(LinkStack& s,int n) {
	MyStack* newstack = new MyStack;
	newstack->data = n;
	newstack->next = s.top;
	s.top = newstack;
}
int Pop(LinkStack& s) {
	if (IsEmpty) {
		cout << "此栈为空" << endl;
	}
	else {
		int n = s.top->data;
		s.top = s.top->next;
		return n;
	}
}
void SecondDisplay(LinkStack&s,int& n) {
	while (1) {
		if (n >=10) {
			int x = n % 10;
			Push(s,x);
			n = n / 10;
		}
		else {
			Push(s, n);
			break;
		}
	}
	MyStack* p = s.top;
	while (1) {
		if (p == NULL)
			break;
		cout << p->data << " ";
		p = p->next;
	}

}
int main() {
	cout << "第一使用递归,请输入你的数字" << endl;
	int n1;
	cin >> n1;
	firstdisplay(n1);//使用递归
	cout << endl;
	LinkStack s;
	Create(s);
	cout << "第二使用非递归,请输入你的数字" << endl;
	int n2;
	cin >> n2;
	SecondDisplay(s, n2);//使用非递归(堆栈)
	
	return 0;
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值