元素出入栈的合法性——栈和队列面试题(4)
2016-09-18 22:53
633 查看
题目要求:元素的出,入栈顺序的合法性。如入栈{1,2,3,4,5,},出栈{4,5,3,2,1}
"test.cpp"
<strong><span style="font-size:18px;">#include<iostream>
using namespace std;
#include<assert.h>
#include<stack>
bool IsLegalOrder(int* arr1,int size1,int* arr2,int size2)
{
assert(arr1);
assert(arr2);
stack<int> s;
int j = 0;
for(int i = 0;i < size1;i++)
{
if(arr1[i] != arr2[j])
{
s.push(arr1[i]);
}
else
{
j++;
}
while(!s.empty() && s.top() == arr2[j])
{
s.pop();
j++;
}
}
if(j == size2)
{
return true;
}
return false;
}
void test()
{
int arr1[] = {1,2,3,4,5};
size_t size1 = sizeof(arr1)/sizeof(arr1[0]);
//int arr2[] = {4,5,3,2,1}; //yes
//int arr2[] = {2,4,5,3,1}; //yes
//int arr2[] = {5,4,3,2,1}; //yes
int arr2[] = {1,2,5,3,4}; //no
size_t size2 = sizeof(arr2)/sizeof(arr2[0]);
bool ret = IsLegalOrder(arr1,size1,arr2,size2);
if(ret)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
int main()
{
test();
return 0;
}</span></strong>
"test.cpp"
<strong><span style="font-size:18px;">#include<iostream>
using namespace std;
#include<assert.h>
#include<stack>
bool IsLegalOrder(int* arr1,int size1,int* arr2,int size2)
{
assert(arr1);
assert(arr2);
stack<int> s;
int j = 0;
for(int i = 0;i < size1;i++)
{
if(arr1[i] != arr2[j])
{
s.push(arr1[i]);
}
else
{
j++;
}
while(!s.empty() && s.top() == arr2[j])
{
s.pop();
j++;
}
}
if(j == size2)
{
return true;
}
return false;
}
void test()
{
int arr1[] = {1,2,3,4,5};
size_t size1 = sizeof(arr1)/sizeof(arr1[0]);
//int arr2[] = {4,5,3,2,1}; //yes
//int arr2[] = {2,4,5,3,1}; //yes
//int arr2[] = {5,4,3,2,1}; //yes
int arr2[] = {1,2,5,3,4}; //no
size_t size2 = sizeof(arr2)/sizeof(arr2[0]);
bool ret = IsLegalOrder(arr1,size1,arr2,size2);
if(ret)
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
int main()
{
test();
return 0;
}</span></strong>
相关文章推荐
- C++基于栈实现铁轨问题
- 浅析C语言中堆和栈的区别
- C语言栈的表示与实现实例详解
- C语言实现颠倒栈的方法
- 算法系列15天速成 第十天 栈
- 一看就懂:图解C#中的值类型、引用类型、栈、堆、ref、out
- Array栈方法和队列方法的特点说明
- java数据结构之java实现栈
- 浅析栈区和堆区内存分配的区别
- 用Java代码实现栈数据结构的基本方法归纳
- 用PHP解决的一个栈的面试题
- 浅谈C#中堆和栈的区别(附上图解)
- C#使用Object类实现栈的方法详解
- JavaScript数据结构与算法之栈详解
- C语言之栈和堆(Stack && Heap)的优缺点及其使用区别
- 如何用C语言、Python实现栈及典型应用
- Python实现栈的方法
- JavaScript数组的栈方法与队列方法详解
- JavaScript数据结构与算法之栈与队列
- JavaScipt中栈的实现方法