Golden programmer interview - face questions 03.03 heap plate (vector (stack))

1. Topic

Heap dish. Imagine a pile of plates, the stack too high may fall down. Therefore, in real life, when the plate heap to a certain height, we will be another pile of dishes.

Please realize the data structure SetOfStacksto simulate this behavior. SetOfStacksIt should be composed of a plurality of stacks, and a new front stack when a stack fills.

In addition, SetOfStacks.push()and SetOfStacks.pop()it should be the same as the ordinary stack operation method (that is to say, pop the returned value (), should the case when only one with the same stack).

Advanced: implement a popAt(int index)method, according to the specified sub-stack performs a pop operation.

When a stack is empty, the stack should be deleted. When the element or the absence of the stack without the stack, pop, popAt should return -1.

示例1:
 输入:
["StackOfPlates", "push", "push", "popAt", "pop", "pop"]
[[1], [1], [2], [1], [], []]
 输出:
[null, null, null, 2, 1, -1]

示例2:
 输入:
["StackOfPlates", "push", "push", "push", "popAt", "popAt", "popAt"]
[[2], [1], [2], [3], [0], [0], [0]]
 输出:
[null, null, null, null, 2, 1, 3]

2. Problem Solving

  • With vector storage stack
class StackOfPlates {
	vector<stack<int>> vs;
	int n;
	int val;
public:
    StackOfPlates(int cap) {
    	n = cap;
    }
    
    void push(int val) {
    	if(n == 0)
    		return;
    	if(vs.empty() || vs.back().size()==n)
    	{	//没有位置,新开一个栈
    		stack<int> s;
    		vs.push_back(s);
    		vs.back().push(val);
    	}
    	else
    		vs.back().push(val);
    }
    
    int pop() {
    	if(!vs.empty())
    	{
    		val = vs.back().top();
    		vs.back().pop();
    		if(vs.back().empty())
    			vs.pop_back();
    		return val;
    	}
    	return -1;
    }
    
    int popAt(int index) {
    	if(index<0 || index >= vs.size())
    		return -1;
    	val = vs[index].top();
    	vs[index].pop();
    	if(vs[index].empty())
    		vs.erase(vs.begin()+index);
    	return val;
    }
};

Here Insert Picture Description

Published 740 original articles · won praise 876 · Views 250,000 +

Guess you like

Origin blog.csdn.net/qq_21201267/article/details/104966870