栈混洗

这里给出栈混洗操作的实现代码,本算法的实现是基于邓俊辉教授所讲的课程《数据结构》中的讲义完成的,当然这里不乏也参考了一些其他的博客以及教材,值得一提的是最初由Knuth所证明正确性的本算法有着线性的时间复杂度,由于本人愚钝,在实现的时候出现了许多问题,在这里感谢给出所有其他类似实现方式的原作者们,有了你们的帮助,这段代码才能得以完成。
#include<iostream>
#include"Stack.h"

using namespace std;

template<class T>
bool stack_permutation(Stack<T> source, Stack<T> dest) 
{
	Stack<T> reversedB, assist;
	while (dest.size())
	{
		reversedB.push(dest.top());
		dest.pop();
	}
	while (source.size())
	{
		assist.push(source.top());
		source.pop();
		if (assist.top() == reversedB.top())
		{
			assist.pop();
			reversedB.pop();
			while (assist.size() && assist.top() == reversedB.top())
			{
				assist.pop();
				reversedB.pop();
			}
		}
	}
	return assist.empty();
}

int main()
{

	Stack<int>obj1;
	
	for (int i = 0; i < 3; i++)
	{
		int x;
		cin >> x;
		obj1.push(x);
	}

	while (true)
	{
		Stack<int>obj2;
		for (int i = 0; i < 3; i++)
		{
			int x;
			cin >> x;
			obj2.push(x);
		}
		bool res;
		cout << (res = stack_permutation(obj1, obj2));
	}

	getchar();
	return 0;
}
值得注意的是:上述代码并没有附上注释,因为我个人认为从变量的命名角度对于读懂这段代码已经足够了。如果你不能够彻底的对其进行理解,那么请你参考邓俊辉教授所编写的《数据结构》教材或者讲义。
发布了17 篇原创文章 · 获赞 17 · 访问量 163

猜你喜欢

转载自blog.csdn.net/dosdiosas_/article/details/105476306