栈和队列的基本操作及其应用

栈和队列的基本操作及其应用

一、实验目的

1、掌握栈和队列的顺序存储结构和链式存储结构,以便在实际中灵活应用。

2、掌握栈和队列的特点,即后进先出和先进先出的原则。

3、掌握栈和队列的基本运算,如:入栈与出栈,入队与出队等运算在顺序存储结构和链式存储结构上的实现。

二、实验内容

本次实验提供4个题目,每个题目都标有难度系数,*越多难度越大,学生可以根据自己的情况选做!

题目一:回文判断(*)

[问题描述]

对于一个从键盘输入的字符串,判断其是否为回文。回文即正反序相同。如“abba”是回文,而“abab”不是回文。

[基本要求]

(1)数据从键盘读入;

(2)输出要判断的字符串;

    (3)利用栈和队列对给定的字符串判断其是否是回文,若是则输出“Yes”,否则输出“No”。

[测试数据]

由学生任意指定。

 

1、总体设计(设计思想)

所谓回文字符串,即该字符串从前往后和从后往前读出来是一样的,所以我们就要判断把一个字符串倒序后是否和原来的字符串相同,如相同,该字符串就是回文字符串,否则不是。

2、详细设计及重要代码:

本题需要一个栈结构,因为栈结构是“先进后出”型,这样就可以先把字符串每个字符依次圧栈,最后出栈且保存在另一个字符串里面,这样两个字符串就互为逆序,此时比较两个字符创是否相同

3、功能截图展示:

 《栈和队列的基本操作及其应用》

4、程序清单

#include<string>
#include<stdio.h>
#include<iostream>
usingnamespace std;       
classStack   //栈类
{
private:
int top;
char *elements;
int Maxsize;
public:
Stack(int s);
~Stack(){delete []elements;}
void push(const char &ch);
char pop();
bool isfull();
bool isempty();
};
Stack::Stack(ints)  //构造函数
{
Maxsize=s;
elements=new char[Maxsize];
top=-1;
}
void Stack::push(constchar &ch)   //圧栈
{
if(!isfull())
        elements[++top]=ch;
else
        return;
}
charStack::pop()    //出栈
{
if(!isempty())
        return elements[top--];
}
boolStack::isfull()    //判满
{
if(top==Maxsize-1)
        return 1;
else
        return 0;
}
bool Stack::isempty()    //判空
{
if(top==-1)
        return 1;
else
        return 0;
}
intmain()
{
string str,str1="";
int len;
while(1)
{
        cout<<"请输入一个字符串(“0”退出):"<<endl;
        cin>>str;
        if(str=="0")break;
        Stack aa(100);
        len=str.length();
        for(int i=0;i<len;i++)
               aa.push(str[i]);
        str1="";
        while(!aa.isempty())
        {
               str1+=aa.pop();
        }
        if(str==str1)
               cout<<"yes"<<endl;
        else
               cout<<"no"<<endl;
}
return 0;
}
 

 

 

题目三:舞伴问题(**)

假设在周末舞会上,男士们和女士们进入舞厅时,各自排成一队。跳舞开始时,依次从男队和女队的队头上各出一人配成舞伴。若两队初始人数不相同,则较长的那一队中未配对者等待下一轮舞曲。现要求写一算法模拟上述舞伴配对问题。

【实验提示】

先入队的男士或女士亦先出队配成舞伴。因此该问题具体有典型的先进先出特性,可用队列作为算法的数据结构。在算法中,假设男士和女士的记录存放在一个数组中作为输入,然后依次扫描该数组的各元素,并根据性别来决定是进入男队还是女队。当这两个队列构造完成之后,依次将两队当前的队头元素出队来配成舞伴,直至某队列变空为止。此时,若某队仍有等待配对者,算法输出此队列中等待者的人数及排在队头的等待者的名字,他(或她)将是下一轮舞曲开始时第一个可获得舞伴的人。

【实验要求】

利用队列实现,存储结构采用顺序或链式均可

1、总体设计(设计思想)

这道题实际上是队列的应用,因为队列遵循“先进先出”的原则,这正好符合这道题的思想。

2、详细设计及重要代码

经过对题意的分析。因此我定义了两个队列,其中一个是男士的队列,一个是女士的队列,搭配舞伴的时候,同时从两个队列的队首获取第一个人,最后剩余的人还能进入下一轮匹配。

3、功能截图展示:

《栈和队列的基本操作及其应用》

4、  程序清单

#include<iostream>
#include<string>
usingnamespace std;
#defineOK 1
#defineERROR 0
typedefstruct People
{
char sex;
char name[100];
struct People *next;
}People,*QPeople;
typedefstruct
{
QPeople front;
QPeople rear;
}ManQueue;
int  InitQueue(ManQueue &q)
{
q.rear = new People[sizeof(People)];
//q.rear = (QPeople)malloc();
if (!q.rear) return ERROR;
q.front = q.rear;
q.front->next = NULL;
return OK;
}
intEnQueue(ManQueue &mq, ManQueue &wq, char  name[], char sex1)
{//入队
QPeople p = (QPeople)malloc(sizeof(People));
if (!p)return ERROR;
p->sex = sex1;
strcpy_s(p->name, 100, name);
p->next = NULL;
char man = 'm';
char woman = 'w';
if (sex1 == man)
{
        mq.rear->next = p;
        mq.rear = p;
}
if (sex1 == woman)
{
        wq.rear->next = p;
        wq.rear = p;
}
return OK;
}
intDeQueue(ManQueue &mq, ManQueue &wq)
{//出队
if (mq.front == mq.rear&&wq.front ==wq.rear) return ERROR;
if (mq.front == mq.rear || wq.front == wq.rear)
{
        cout << "无匹配对象" << endl;
        return ERROR;
}
QPeople p = (QPeople)malloc(sizeof(People));
if (!p)return ERROR;
QPeople q = (QPeople)malloc(sizeof(People));
if (!q)return ERROR;
p = mq.front->next;
q = wq.front->next;
cout << "匹配信息为 : " << endl;
while (p != NULL&&q != NULL)
{
        cout << "男 :" << p->name << "   " << "女 : " << q->name<< endl;
        p = p->next;
        q = q->next;
}
cout << "等待下一轮的信息为:" << endl;
if (p != NULL)
{
        cout << "男  " << p->name;
        int i = 0;
        while (p != NULL)
        {
               p = p->next;
               i++;
        }
        cout << "   等待人数为:" << i << endl;
}
if (q != NULL)
{
        cout << "女  " << q->name;
        int j = 0;
        while (q != NULL)
        {
               q = q->next;
               j++;
        }
        cout << "   等待人数为:" << j << endl;
}
return OK;
}
intShow(ManQueue Q, ManQueue P)
{//显示男女队
QPeople p = (QPeople)malloc(sizeof(People));
if (!p)return ERROR;
p = Q.front->next;
QPeople q = (QPeople)malloc(sizeof(People));
if (!q)return ERROR;
q = P.front->next;
while (p != NULL&&q != NULL)
{
        cout << p->name <<"       " << q->name<< endl;
        p = p->next;
        q = q->next;
}
while (p != NULL)
{
        cout << p->name << endl;
        p = p->next;
}
while (q != NULL)
{
        cout << "        " << q->name <<endl;
        q = q->next;
}
return OK;
}
intmain()
{
char name[100];
char sex;
ManQueue man;
ManQueue woman;
InitQueue(man);
InitQueue(woman);
cout<<"=========================="<<endl;
cout<<"===欢迎进入舞伴匹配系统==="<<endl;
cout<<"=========================="<<endl;
cout << "输入总人数:" << endl;
int number;
cin >> number;
for (int i = 0; i < number; i++)
{
        cout << "输入第" << i + 1 <<"个人的信息  " << endl;;        
        cout << "姓名(字符串): ";
        cin >> name;
        cout << "性别(w/m): ";
        cin >> sex;
        EnQueue(man, woman, name, sex);
}
cout << endl;
cout << "显示男女队的信息:" << endl;
cout << "男      女" << endl;
Show(man, woman);
cout << endl;
DeQueue(man, woman);
return 0;
}

 

 

题目四:Rails(***)

[Description]

There is a famous railway stationin PopPush City. Country there is incredibly hilly.The station was built in last century. Unfortunately, funds were extremelylimited that time. It was possible to establish only a surface track. Moreover,it turned out that the station could be only a dead-end one (see picture) anddue to lack of available space it could have only one track.

The local tradition is that every train arriving from thedirection A continues in the direction B with coaches reorganized in some way.Assume that the train arriving from the direction A has N <= 1000 coachesnumbered in increasing order 1, 2, …, N. The chief for train reorganizationsmust know whether it is possible to marshal coaches continuing in the directionB so that their order will be a1, a2, …, aN. Help him and write a programthat decides whether it is possible to get the required order of coaches. Youcan assume that single coaches can be disconnected from the train before theyenter the station and that they can move themselves until they are on the trackin the direction B. You can also suppose that at any time there can be locatedas many coaches as necessary in the station. But once a coach has entered thestation it cannot return to the track in the direction A and also once it hasleft the station in the direction B it cannot return back to the station.

[Input]

The input consists ofblocks of lines. Each block except the last describes one train and possiblymore requirements for its reorganization. In the first line of the block thereis the integer N described above. In each of the next lines of the block thereis a permutation of 1, 2, …, N. The last line of the block contains just 0.

The last block consists of just one line containing 0.

[Output]

The output containsthe lines corresponding to the lines with permutations in the input. A line ofthe output contains Yes if it is possible to marshal the coaches in the orderrequired on the corresponding line of the input. Otherwise it contains No. Inaddition, there is one empty line after the lines corresponding to one block ofthe input. There is no line in the output corresponding to the last “null”block of the input.

[Sample Input]

5

1 2 3 4 5

5 4 1 2 3

0

6

6 5 4 3 2 1

0

0

[Sample Output]

Yes

No

 

Yes

 

 

1、总体设计(设计思想)

栈的应用的简单题,就是给你一个出栈的序列,判断这段序列是否合法,

简单模拟就行了

2、详细设计及重要代码

从1~n依次圧栈,圧栈的同时,比较栈顶元素与所求序列的首元素进行比较,

设置计数器记录出栈元素个数,如改数值等于n,则输出yes,否则输出no。

3、功能截图展示:

 《栈和队列的基本操作及其应用》

4、  程序清单

 

#include<string>
#include<stdio.h>
#include<iostream>
using namespacestd;  
int a[1005];
class Stack   //栈类
{
private:
        int top;
        int *elements;
        int Maxsize;
public:
        Stack(int s);
        //~Stack(){delete []elements;}
        void push(const int &ch);
        int pop();
        bool isfull();
        bool isempty();
        int ttop();
};
Stack::Stack(int s)  //构造函数
{
        Maxsize=s;
        elements=new int[Maxsize];
        top=-1;
}
void Stack::push(constint &ch)   //圧栈
{
        if(!isfull())
               elements[top++]=ch;
        else
               return;
}
int Stack::pop()    //出栈
{
        if(!isempty())
               return elements[top--];
}
int Stack::ttop()
{
        if(!isempty())
               return elements[top-1];
}
boolStack::isfull()    //判满
{
        if(top==Maxsize-1)
               return 1;
        else
               return 0;
}
boolStack::isempty()    //判空
{
        if(top==-1)
               return 1;
        else
               return 0;
}
int main()
{
    int n,i,k;
    while(cin>>n,n)
    {
       Stack s(100);//设立一个栈储存按顺序进栈的序列 (一个空栈)
        while(cin>>a[0]&&a[0])
        {
            for(i=1;i<n;i++)
                cin>>a[i];//要进行判断出栈的序列
            for(i=1,k=0;i<=n;i++)
            {
                s.push(i);//进栈
                while(s.ttop()==a[k])//判断栈顶元素和a数组是否相等
                {
                    if(!s.isempty()) s.pop();//栈不为空就出栈
                    k++;//判断下一个位置
                    if(s.isempty()) break;//直到栈空就结束循环
                }
            }
            if(k==n)printf("Yes\n");//完全匹配就输出yes
           else printf("No\n");
        }
       cout<<endl;
    }
    return 0;
}
    原文作者:舞伴问题
    原文地址: https://blog.csdn.net/initiallysunny/article/details/53494558
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞