剑指offer 第五题:用两个栈实现队列

题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:栈 先进后出,队列 先进先出
1 2 3 栈 3 2 1
1 2 3 队列 1 2 3
stack1进栈后为1 2 3 出栈并保存在stack2中为3 2 1,stack2出栈就和队列一致了。
push,在stack1中进行,pop则把stack1中的元素输出到stack2中,stack2为空才再次进栈。

class Solution
{
public:
    void push(int node) {
        stack1.push(node);
    }
    int pop() {
        if(stack2.empty())
        {
            while(!stack1.empty())
            {
                stack2.push(stack1.top());
                stack1.pop();
            }
        }
        int data=stack2.top();
        stack2.pop();
        return data;
    }
private:
    stack<int> stack1;
    stack<int> stack2;
};

python

# -*- coding:utf-8 -*-
class Solution:
    def __init__(self):
        self.stack1=[]
        self.stack2=[]
    def push(self, node):
        self.stack1.append(node);
        # write code here
    def pop(self):
        if len(self.stack2)==0:
            while len(self.stack1)!=0:
                self.stack2.append(self.stack1.pop())
        return self.stack2.pop()
        # return xx

pop()与remove的区别

1.pop()方法,传递的是待删除元素的index,返回值为删除的元素:
x = ['a', 'b', 'c', 'd']
x.pop(2) #默认删除后一位,超出范围会报错
print x
['a', 'b', 'd']
2. remove()传递待删除元素:
x = ['a', 'b', 'a', 'c', 'd']
x.remove('a') #不包含则报错
print x
['b', 'a', 'c', 'd']

猜你喜欢

转载自blog.csdn.net/zd_nupt/article/details/80695718