使用循环队列重新排列顺序栈元素算法实现
#include
stack
void init(int len) { for (int i = 0; i < 2 * len; ++i) { int elem; cin >> elem; seqStack.push(elem); } }
void exchange() { while (!seqStack.empty()) { int elem = seqStack.top(); seqStack.pop(); cirQueue.push(elem); } for (int i = 1; i <= 2 * n; ++i) { int elem = cirQueue.front(); cirQueue.pop(); if (i % 2 == 0) { cirQueue.push(elem); } else { seqStack.push(elem); } } while (!seqStack.empty()) { int elem = seqStack.top(); seqStack.pop(); cirQueue.push(elem); } while (!cirQueue.empty()) { int elem = cirQueue.front(); cirQueue.pop(); seqStack.push(elem); } }
void printStack() { while (!seqStack.empty()) { cout << seqStack.top() << ' '; // 将双引号改为单引号 seqStack.pop(); } cout << endl; }
int main() { cin >> n; init(n); exchange(); printStack(); return 0; }
原文地址: https://www.cveoy.top/t/topic/paB5 著作权归作者所有。请勿转载和采集!