您的位置:首页 > 产品设计 > UI/UE

Implement Stack using Queues && Implement Queue using Stacks

2015-07-23 01:42 671 查看
Implement Stack using Queues

class Stack {
private:
queue<int> q;
public:
// Push element x onto stack.
void push(int x) {
queue<int> t;
while (!q.empty()) {
t.push(q.front());
q.pop();
}
q.push(x);
while(!t.empty()) {
q.push(t.front());
t.pop();
}
}

// Removes the element on top of the stack.
void pop() {
q.pop();
}

// Get the top element.
int top() {
while (!q.empty()) return q.front();
}

// Return whether the stack is empty.
bool empty() {
return q.empty();
}
};


Implement Queue using Stacks

class Queue {
private:
stack<int> s;
public:
// Push element x to the back of queue.
void push(int x) {
stack<int> t;
while (!s.empty()) {
t.push(s.top());
s.pop();
}
s.push(x);
while(!t.empty()) {
s.push(t.top());
t.pop();
}
}

// Removes the element from in front of queue.
void pop(void) {
s.pop();
}

// Get the front element.
int peek(void) {
if (!s.empty()) return s.top();
}

// Return whether the queue is empty.
bool empty(void) {
return s.empty();
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: