zoukankan      html  css  js  c++  java
  • 栈的应用

    1~n依次入栈,输入1~n之间的数(出栈顺序),顺序不限,判断输入的出栈顺序是否存在

    样例输入:

    5

    1 2 3 4 5

    5

    5 4 1 2 3

    6

    6 5 4 3 2 1

    样例输出:

    yes

    no

    yes

     1 #include<cstdio>
     2 #include<iostream>
     3 using namespace std;
     4 const int maxn=1000+10;
     5 int n,target[maxn];
     6 int main()
     7 {
     8     while(cin>>n)
     9     {
    10         int stack[maxn],top=0;
    11         int A=1,B=1;
    12         for(int i=1;i<=n;i++)
    13         cin>>target[i];
    14         int ok=1;
    15         while(B<=n)
    16         {
    17             if(A==target[B]){A++;B++;}
    18             else if(top && stack[top]==target[B]){top--;B++;}
    19             else if(A<=n){stack[++top]=A++;}//如果是top++先赋值再+1,那么栈顶元素就是随机的了。
    20             else {ok=0;break;}
    21         }
    22        printf("%s
    ",ok?"yes":"no");
    23     }
    24     return 0;
    25 }

    STL栈的实现

     1 #include<cstdio>
     2 #include<iostream>
     3 #include<stack>
     4 using namespace std;
     5 const int maxn=1000+10;
     6 int n,target[maxn];
     7 int main()
     8 {
     9     while(cin>>n)
    10     {
    11         stack<int> s;
    12         int A=1,B=1;
    13         for(int i=1;i<=n;i++)
    14         cin>>target[i];
    15         int ok=1;
    16         while(B<=n)
    17         {
    18             if(A==target[B]){A++;B++;}
    19             else if(!s.empty() && s.top()==target[B]){s.pop();B++;}
    20             else if(A<=n)s.push(A++);
    21             else {ok=0;break;}
    22         }
    23        printf("%s
    ",ok?"yes":"no");
    24     }
    25     return 0;
    26 }
  • 相关阅读:
    Spring IoC容器实现
    Spring IoC简介及使用
    tomcat使用及原理
    tomcat的连接数与线程池
    tomcat配置文件server.xml
    java源码之Comparable和Comparator
    java源码之TreeSet
    25 二叉搜索树与双向链表
    24 复杂链表的复制
    条款04:确定对象被使用前已被初始化
  • 原文地址:https://www.cnblogs.com/WHLdbk/p/5752791.html
Copyright © 2011-2022 走看看