1. 程式人生 > >資料結構與演算法題目集7-18——銀行業務佇列簡單模擬

資料結構與演算法題目集7-18——銀行業務佇列簡單模擬

我的資料結構與演算法題目集程式碼倉:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原題連結:https://pintia.cn/problem-sets/15/problems/825

題目描述:

知識點:佇列

思路:用佇列模擬

時間複雜度和空間複雜度均是O(N)。

C++程式碼:

#include<iostream>
#include<queue>

using namespace std;

int N;
queue<int> qa, qb, result;

int main() {
	scanf("%d", &N);
	int num;
	for(int i = 0; i < N; i++) {
		scanf("%d", &num);
		if(num % 2 == 0) {
			qb.push(num);
		} else {
			qa.push(num);
		}
	}
	while(!qa.empty() || !qb.empty()) {
		if(!qa.empty()) {
			result.push(qa.front());
			qa.pop();
			if(!qa.empty()) {
				result.push(qa.front());
				qa.pop();
			}
		}
		if(!qb.empty()) {
			result.push(qb.front());
			qb.pop();
		}
	}
	while(!result.empty()){
		printf("%d", result.front());
		result.pop();
		if(!result.empty()){
			printf(" ");
		}else{
			printf("\n");
		}
	}
	return 0;
}

C++解題報告: