数据结构基础_栈和队列

栈和队列

线性表是“所有元素排成一列”的数据结构。栈和队列是两种特殊的线性表。

卡片游戏

题目:桌面上有一叠牌,从第一张牌到最后面1~n。当至少还剩两张牌时。把第一张牌丢掉,然后把新的第一张放在整叠牌的后面。

输入n,输出每次丢处的牌,以及最后剩下的牌,符合FIFO原则。用一个数组queue来实现这个队列,再设两个指针front和rear。

  输入:

    7

  输出:

    1 3 5 7 4 2 6

 1 #include <stdio.h>
 2 const int MAXN=50;
 3 int queue[MAXN];
 4 int main() {
 5     int n,i,front,rear;
 6     scanf("%d",&n);
 7     for(i=0;i<n;i++){
 8         queue[i]=i+1;
 9     }
10     front=0;rear=n;
11     while(front<rear){
12         printf("%d ",queue[front++]);
13         queue[rear++]=queue[front++];
14     }
15     return 0;
16 }

 

  嗯,queue[rear++]=queue[front++]读写了非法内存,至于怎么读写,不知道。。。只知道最后rear=2n;不符合题目。

  解决:要么把数组开大一点,要么采取一种称为循环队列的技术,重用已经出对元素占用的空间。

   queue容器介绍别人家的整理

 1 #include<queue>
 2 #include<cstdio>
 3 using namespace std;
 4 /*
 5 stdio.h是以往的C和C++的头文件,cstdio是标准C++(STL),且cstdio中的函数都是定义在一个名称空间std里面的,
 6 如果要调用这个名字空间的函数,必须得加std::或者在文件中声明using namespace std。
 7 */
 8 queue<int> q; //使用前需定义一个queue变量,且定义时已经初始化
 9 int main(){
10     int n;
11     scanf("%d",&n);
12     for(int i=0;i<n;i++)q.push(i+1);//进队列
13     while(!q.empty())//重复使用时,用这个初始化
14     {
15         printf("%d ",q.front());
16         q.pop();//抛弃队首元素
17         q.push(q.front());
18         q.pop();
19     }
20     return 0;
21 }

铁轨

 题目:有n节车厢从A方向驶入车站,按照进站的循序编号为1~n。只有A→C进站,C→B方向出站行驶。

  车厢C符合后进先出LIFO原则。实现栈只需要一个数组stack和栈顶指针。

  输入:

    5
    1 2 3 4 5
    5
    5 4 1 2 3
    6
    6 5 4 3 2 1

  输出:

    Yes
    No
    Yes

 1 #include <stdio.h>
 2 const int MAXN=1000+10;
 3 int n,target[MAXN],stack[MAXN];
 4 int main() {
 5     while(scanf("%d",&n)!=EOF){
 6         int top=0;
 7         int A=1,B=1;
 8         for(int i=1;i<=n;i++)
 9             scanf("%d",&target[i]);
10         int ok=1;
11         while(B<=n){
12             if(A==target[B]){A++;B++;}
13             else if(top&& stack[top]==target[B]){top--;B++;}
14             else if(A<=n){stack[++top]=A;A++;}
15             else {ok=0;break;}
16         }
17         printf("%s\n",ok?"Yes":"No");
18     }
19     return 0;
20 }

   使用STL栈来实现。同上修改stack栈的处理。

 1 #include<cstdio>
 2 #include<stack>
 3 using namespace std;
 4 const int MAXN=1000+10;
 5 int n,target[MAXN];
 6 int main(){
 7     while(scanf("%d",&n)!=EOF){
 8         stack<int> s;
 9         int A=1,B=1;
10         for(int i=1;i<=n;i++)
11             scanf("%d",&target[i]);
12         int ok=1;
13         while(B<=n){
14             if(A==target[B]){A++;B++;}
15             else if(!s.empty()&& s.top()==target[B]) {s.pop();B++;}
16             else if(A<=n) s.push(A++);
17             else {ok=0;break;}
18         }
19         printf("%s\n",ok?"Yes":"No");
20     }
21     return 0;
22 }
posted @ 2017-08-03 10:38  JanFangZ  阅读(223)  评论(0编辑  收藏  举报