Queues and Stacks __ queues

Source: Internet
Author: User
Queues Card Games

There is a stack of cards on the table, starting with the first card (that is, the card at the top) to be numbered 1-n. When you have at least two cards left, do the following: Throw the first card away and put the new first one at the end of the stack. Enter n, output the cards thrown each time, and the last remaining cards.
Sample input: 7
Sample output: 1 3 5 7 4 2 6

# include<iostream>
# include<queue>
using namespace std;
queue<int> Q;
int main ()
{
    int n;
    cin>>n;
    for (int i=0;i<n;i++)
        Q.push (i+1);
    while (!q.empty ())
    {
        cout<<q.front () << "";
        Q.pop ();
        Q.push (Q.front ());
        Q.pop ();
    }
    return 0;
}
Stack
# include<cstdio>
# include<algorithm>
using namespace std;
const int MAXN=1000+10;
int TARGET[MAXN];
int main ()
{
    int n;
    while (scanf ("%d", &n) ==1)
    {
        int stack[maxn],top=0;
        int a=1,b=1;
        for (int i=1;i<=n;i++)
            scanf ("%d", &target[i]);
        int ok=1;
        while (b<=n)
        {
            if (A==target[b]) {a++; b++;} No need c
            else if (Top&&stack[top]==target[b]) {top--; b++;}
            else if (a<=n) {stack[++top]=a++}
            else {ok=0;break;}
        }
        printf ("%s\n", OK?) Yes ":" no ");
    }
    return 0;
}

using STL to implement stack

# include<cstdio> # include<algorithm> # include<stack> using namespace std
;
const int MAXN=1000+10;
int TARGET[MAXN];
    int main () {int n;
        while (scanf ("%d", &n) ==1) {//int stack[maxn],top=0;
        Stack<int> s;
        int a=1,b=1;
        for (int i=1;i<=n;i++) scanf ("%d", &target[i]);
        int ok=1; while (b<=n) {if (A==target[b]) {a++; b++;} No need C else if (!s.empty () && s.top () ==target[b]) {s.pop ();
            b++;}
            else if (a<=n) {s.push (a++);}
        else {ok=0;break;} printf ("%s\n", OK?)
    Yes ":" No ");
return 0; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.