1.用栈实现队列
用两个栈来实现队列
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty())
{
/*stIn的数据弹出直到为空*/
while(!stIn.empty())
{
stOut.push(stIn.top());//将stIn的数据弹到stOut
stIn.pop();
}
}
/*再把stOut的数据弹出*/
int result = stOut.top();
stOut.pop();
return result;
}
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
bool empty() {
return stIn.empty()&&stOut.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
2.队列实现栈
class MyStack {
public:
queue<int> que1;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int size = que1.size()-1;
//将前n-1个弹出
while(size--)
{
que1.push(que1.front());
que1.pop();
}
//将队列最后一个元素弹出即为栈顶元素
int result = que1.front();
que1.pop();
return result;
}
int top() {
//返回队列最后一个元素即为栈的入口元素
return que1.back();
}
bool empty() {
return que1.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
3.有效的括号
每一个括号必定是成对存在
1.如果正确,则最后栈为空,否则遍历完之后栈不为空(左括号多了)
2.如果出栈时括号与当前括号不匹配,则false (顺序错乱)
3.还没遍历完,栈就空了,false (右括号多了)
4.一定是偶数
C语言代码:
typedef struct stack{
char *str;
int top;
int size;
}Stack;
bool isValid(char * s){
int i=0;
// for(i=0;s[i]!='\0';i++)
// {
// i++;
// }
Stack *stac = (Stack*)malloc(sizeof(Stack));
stac->str = (char*)malloc(strlen(s)*sizeof(char));
stac->top=0;
stac->size = 1;
for(i=0;s[i]!='\0';i++)
{
if(s[i]=='(')
{
printf("(\r\n");
stac->str[stac->top] = ')';
stac->top++;
stac->size++;
}
else if(s[i]=='[')
{
stac->str[stac->top] = ']';
stac->top++;
stac->size++;
}
else if(s[i]=='{')
{
stac->str[stac->top] = '}';
stac->top++;
stac->size++;
}
else if(s[i]==')'||s[i]==']'||s[i]=='}')
{
stac->top--;
if(stac->top<0)
{
return false;
}
if(s[i]!=(stac->str[stac->top]))
{
printf("1false\r\n");
return false;
}
else if(stac->size == 0)
{
printf("2false\r\n");
return false;
}
else
{
//stac->top--;
stac->size--;
}
}
}
printf("stac->top = %d\r\n",stac->top);
if(stac->top !=0)
{
printf("3false\r\n");
return false;
}
else
{
printf("true\r\n");
return true;
}
}
C++实现如下:
class Solution {
public:
stack<char> stack1;
bool isValid(string s) {
if(s.size()%2!=0)
{
return false;
}
for(int i=0;i<s.size();i++)
{
if(s[i]=='(')
{
stack1.push(')');
}
else if(s[i]=='[')
{
stack1.push(']');
}
else if(s[i]=='{')
{
stack1.push('}');
}
else if(s[i]==')'||s[i]==']'||s[i]=='}')
{
if(stack1.empty())
{
return false;
}
else
{
if(stack1.top() != s[i])
{
return false;
}
else
{
stack1.pop();
}
}
}
}
if(stack1.empty())
{
return true;
}
else
{
return false;
}
}
};