栈和队列理论基础
- 栈和队列都是一种容器适配器,container adapter,可以选择底层的容器
stack.push()
stack.pop(): no return value
stack.top()
stack.push()
queue.push()
queue.front()
queue.pop()
queue.back()
232 用栈组成队列
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (`push`, `peek`, `pop`, and `empty`).
Implement the `MyQueue` class:
- `void push(int x)` Pushes element x to the back of the queue.
- `int pop()` Removes the element from the front of the queue and returns it.
- `int peek()` Returns the element at the front of the queue.
- `boolean empty()` Returns `true` if the queue is empty, `false` otherwise.
要点:
- 用两个栈
错误:
- 必须要out栈空的时候,才能push in栈
- stack.pop()返回值
225 用队列实现栈
Implement a last-in-first-out (LIFO) stack using only two queues. The implemented stack should support all the functions of a normal stack (`push`, `top`, `pop`, and `empty`).
Implement the `MyStack` class:
- `void push(int x)` Pushes element x to the top of the stack.
- `int pop()` Removes the element on the top of the stack and returns it.
- `int top()` Returns the element on the top of the stack.
- `boolean empty()` Returns `true` if the stack is empty, `false` otherwise.
要点:
- 用一个或者两个队列
错误:
20 匹配括号
Given a string `s` containing just the characters `'('`, `')'`, `'{'`, `'}'`, `'['` and `']'`, determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
1. Open brackets must be closed in the correct order.
1. Every close bracket has a corresponding open bracket of the same type.
要点:
- 栈:适合处理对称匹配问题
错误:
- 需要压入对称字符到栈上