# 题目

输入：pushed = [1,2,3,4,5], popped = [4,5,3,2,1]

push(1), push(2), push(3), push(4), pop() -> 4,
push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1


输入：pushed = [1,2,3,4,5], popped = [4,3,5,1,2]



1. 0 <= pushed.length == popped.length <= 1000
2. 0 <= pushed[i], popped[i] < 1000
3. pushed 是 popped 的排列。

1.stack

2.vector

# 思路

输入：pushed = [1,2,3,4,5], popped = [4,5,3,2,1] 输出：true

输入：pushed = [1,2,3,4,5], popped = [4,3,5,1,2] 输出：false

flag=false;

auto pushIt=pushed.begin();

{

1.1 有数可以入：pushIt!=pushed.end() ：

{

data.push(*pushIt);

pushIt++;

}

1.2 否则无数可入： break;

}

{

data.pop();

popIt++:

}

}

# 代码

newcoder

class Solution {
public:
bool IsPopOrder(vector<int> pushV,vector<int> popV) {
bool flag = false;

if(!pushV.size()||!popV.size())
return flag;

//定义栈，读取迭代器
stack<int> data;
auto  pushNext=pushV.begin();
auto popNext=popV.begin();

while(popNext!=popV.end())
{ //入栈
if(data.empty()||data.top()!=*popNext)
{
//pushed没有可入栈元素，返回
if(pushNext==pushV.end())
break;
else//否则，压入栈中
{
data.push(*pushNext);
pushNext++;
}
}
else//pop
{
data.pop();
popNext++;//访问下个poped元素
}

}

//如果压入栈为空，且poped序列访问完，则返回真
if(data.empty()&&popNext==popV.end())
flag=true;

return flag;
}
};

leetcode

class Solution {
public:
bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
if(pushed.empty()&&popped.empty())
return true;

if(pushed.size()!=popped.size())
return false;

bool flag=false;

//局部变量
auto pushIt=pushed.begin();
auto popIt=popped.begin();
stack<int> data;

while(popIt!=popped.end())
{
//进栈
if(data.empty()||data.top()!=*popIt)
{
//无数可进
if(pushIt==pushed.end())
break;
else
{
//进栈，pushIt++
data.push(*pushIt);
pushIt++;
}
}
else
//出栈
{
data.pop();
popIt++;
}
}

return (popIt==popped.end()&& data.empty()) ? true : flag ;

}
};

# 问题

### 1. vector::begin/end

#include <iostream>
#include <vector>

int main ()
{
std::vector<int> myvector;
for (int i=1; i<=5; i++) myvector.push_back(i);

std::cout << "myvector contains:";
for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';

return 0;
}
myvector contains: 1 2 3 4 5

posted @ 2019-02-08 21:37  lightmare  阅读(79)  评论(0编辑  收藏