C++判断出栈顺序

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/coolsunxu/article/details/78175350
#include<iostream>
#include<stack>
using namespace std;

void Ini_Visited(bool *Visited,int *C,int n) {
	for (int i = 0; i < n; i++) {
		Visited[i] = false;
		C[i] = 0;
	}
}

void Input_A_B(int *A, int *B, int n) {//输入元素
	cout << "请输入进栈的次序:" << endl;
	for (int i = 0; i < n; i++) {
		cin >> A[i];
	}
	cout << "请输入要检测的序列:" << endl;
	for (int i = 0; i < n; i++) {
		cin >> B[i];
	}
}

int Count_C(int *C) {//返回不为零的个数
	int i;
	for (i = 0; i < 100; i++) {
		if (C[i] == 0) {
			break;
		}
	}
	return i;
}

bool Is_In_C(int *C,int a,int n) {//判断元素是否存在C中
	for (int i = 0; i < n; i++) {
		if (C[i] == a) {
			return true;
		}
	}
	return false;
}

int Locate(int *A, int a,int n) {//判断元素在A的位置
	int locate;
	for (int i = 0; i < n; i++) {
		if (A[i] == a) {
			locate = i;
			break;
		}
	}
	return locate;
}

void Print(int *C,int n ) {
	int i;
	for (i = 0; i < n; i++) {
		if (C[i] != 0) {
			cout << C[i] << " ";
		}
	}
}

void Judge(int *A, int *B, int *C, bool *Visited, int n) {
	bool flag = true;
	stack<int> s;
	int i = 0;
	while (i < n) {
		int locate = Locate(A, B[i], n);
		for (int j = 0; j <= locate; j++) {
			if ((Visited[j] == false && Is_In_C(C, A[j], n)==false)) {
				s.push(A[j]);
				C[Count_C(C)] = A[j];
			}
		}

		Print(C,n);
		cout << endl;

		if (s.top() == B[i]) {
			s.pop();
			Visited[locate] = true;//已经出栈了
			i++;
			C[Count_C(C) - 1] = 0;
		}
		else {
			flag = false;
			break;
		}
	}

	if (flag) {
		cout << "正确" << endl;
	}
	else {
		cout << "错误" << endl;
	}
}

void Destroy(int *A, int *B, bool *Visited) {
	delete A;
	delete B;
	delete Visited;
}

int main() {
	int C[100];
	int n;
	cout << "请输入元素个数:";
	cin >> n;
	int *A = new int[n];
	int *B = new int[n];
	bool *Visited = new bool[n];//判断是否已经出栈
	Ini_Visited(Visited, C,n);//初始化
	Input_A_B(A, B, n);//输入元素
	Judge(A, B, C, Visited, n);
	Destroy(A, B, Visited);
	system("pause");
	return 0;

}

展开阅读全文

没有更多推荐了,返回首页