train.cpp

来自「经典c++程序的实现」· C++ 代码 · 共 69 行

CPP
69
字号

// alist.cpp

#include <stdio.h>
#include <iostream.h>
#include <assert.h>

#include "..\include\book.h"

typedef int ELEM;

//#include "..\include\link.h"
//#include "..\include\lstack.h"
#include "..\include\trainastack.h"

Stack userstack, destination;

int n;

void procedure(int step)  {
	if (step <= n)  {        // 待处理的车辆数小于等于总数
		if (!userstack.isEmpty())  {    // 车站(栈)中不为空
			destination.push(userstack.pop());    // 把车站(栈)中车辆出栈			
			if (destination.length() == n)   // 打印满了的序列
				destination.print();
			procedure(step);
			userstack.push(destination.pop());   // 回溯
		}
		if (step <= n)  {
			userstack.push(step);
			procedure(step+1);
			destination.push(userstack.pop());   // 回溯
		}
	}	
	else {		
		while (!userstack.isEmpty()) 
			destination.push(userstack.pop());    // 把车站(栈)中车辆出栈			
		if (destination.length() == n)
			destination.print();		
		while (!destination.isEmpty()) 
			userstack.push(destination.pop());						
	}    
}

/*
void trainarr() {
	Stack trainst(n);
	list  arr(n);
	int k;

	for (int i=0; i<n; i++)
		trainst.push(i+1);
	for (int k=n-1; k>=0; k--) {
		while (!trainst.isEmpty())     // 把栈中所有内容都倒到出栈数组
			arr.append(train.pop());
		print(arr);
		for (i=1; i<k; i++) {          // 从数组中倒回来k个
			arr.setPos(arr.length());
			trainst.push(arr.remove());
		}
	}
}
*/

void main()  {
	cout << "Please input n" << endl;
	cin >> n;
	procedure(1);
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?