• 栈的应用


    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 }
  • 相关阅读:
    3.7日复习
    作业
    小米官网需要的数据
    EL&JSTL
    变量和运算符
    jsp
    session的应用----验证码
    restframework-总结
    Django-Rest-Framework部分源码流程分析
    Django-Rest-Framework
  • 原文地址:https://www.cnblogs.com/WHLdbk/p/5752791.html
Copyright © 2020-2023  润新知