225. Implement Stack using Queues

来源:互联网 发布:怎么面试美工 编辑:程序博客网 时间:2024/06/05 07:28

这道题考查的是用队列Queue来模拟栈Stack,也是完成几个接口,pop,push,top…..先理清思路,再写代码。
描述:
Implement the following operations of a stack using queues.

push(x) – Push element x onto stack.
pop() – Removes the element on top of the stack.
top() – Get the top element.
empty() – Return whether the stack is empty.

思路:

要达到后进先出的规则,结合队列,那我们每次要定位的就是队列的尾部元素,无论是删除pop,还是top求栈顶元素。
pop:而队列只支持删除头部节点,那我们可以试着将尾部节点变成头部节点,怎么变成头部节点呢?—–我们可以使用两个队列q1,q2,在pop的时候将一个队列(假设为q1)中的前size-1个存放到另外一个队列(q2)中,那么这时候q1只剩下了原先的尾部节点,也就是我们要定位的节点。这时候操做完了,q1空了,q2存储着剩下的元素。下次再要pop操作同理进行即可。

top:同理我们需要定位到尾部元素,这时候假设q1有元素,将q1中的n-1个元素先存放到q2中(存放的过程q1在不断pop,q2在push),到最后只剩下尾部元素了,将其提取到一个临时变量,然后再继续将其存储到q2中,再删除q1,这时候q1空了,q2相当于拷贝了一份q1。我们也找到了q1的尾部元素,将其返回即可。

push:由上我们知道,只有一个队列存放有效数据,相对的另外一个队列是在进行不同操作时用作转存有效数据,所以我们push的时候看哪个队列不为空,就往其中push数据,都为空的时候,就随便了,这里我们指定q1.

empty::在q1和q2均为空的时候,这个模拟栈无元素。

C++

class Stack {public:    queue<int> q1;    queue<int> q2;    // Push element x onto stack.    void push(int x) {        if(q1.empty() && q2.empty()){                q1.push(x);        }        else if(!q2.empty()){                q2.push(x);        }        else if(!q1.empty()){                q1.push(x);        }    }    // Removes the element on top of the stack.    void pop() {        if(!q1.empty()){           int size = q1.size()-1;           for(int i = 0;i < size;i++){              q2.push(q1.front());              q1.pop();           }           q1.pop();        }        else{            int size = q2.size()-1;            for(int i = 0;i < size;i++){              q1.push(q2.front());              q2.pop();           }            q2.pop();        }    }    // Get the top element.    int top() {        if(q2.empty()){           int size = q1.size()-1;           for(int i = 0;i < size;i++){              q2.push(q1.front());              q1.pop();           }           int temp = q1.front();           q2.push(temp);           q1.pop();           return temp;        }        else{           int size = q2.size()-1;           for(int i = 0;i < size;i++){                q1.push(q2.front());                q2.pop();           }            int temp = q2.front();            q1.push(temp);            q2.pop();            return temp;        }    }    // Return whether the stack is empty.    bool empty() {        return q1.empty()&&q2.empty()?1:0;    }};

用python做就完全不用想这么多,因为list的强大:

class Stack(object):    def __init__(self):        self.q=[]    def push(self, x):        self.q.append(x)    def pop(self):        if not self.empty():            self.q = self.q[:-1]        #list的-1表示最后一个元素,:是前开后闭----[:),包含前面不不包含后面    def top(self):        return self.q[-1]    def empty(self):        return len(self.q) == 0
0 0
原创粉丝点击