循环队列的题

队列

Description

输入的第一行为一个自然数n,表示要求构造的顺序循环队列空间数。 
第二行为操作次k,接下来k行为出队入队操作,每行各代表一次操作。
入队用in表示,出队用out表示,如果是入队,则in隔一空格后为一整数,表示入队元素值。 

Input

输出完成所有入队出队操作后,一次性出队元素。用一个空格隔开。可以假定队在完成所有操作后不为空。 

Output

输出完成所有入队出队操作后,一次性出队元素。用一个空格隔开。可以假定队在完成所有操作后不为空。  

Sample Input

4 
7 
in 1 
in 2 
in 5 
in 6 
out 
out 
in 8 

Output

5 8

下面是我用C语言双向循环链表进行的处理(”*&”用了引用,自己查百度)

// tetete.cpp : Defines the entry point for the console application.
//结构体存放了两个必要的指针,一个变量存放值,一个变量存放标识符,表示这个结构体是否有值(入队置true,反之置false)

#include <stdio.h>
#include <string.h>

typedef struct line{
    int value;
    line *pre;
    line *next;
    bool isvalue;
}line;

//根据参数决定链表大小,返回链表的头指针
line * createNode(int count){
    line *first = NULL, *last = NULL;
    line *node = NULL;
    for(int i = 0; i < count; i++){
        node = new line;
        /////////初始化
        node->isvalue = false;
        node->value = -1;
        /////////
        if(first == NULL){
            first = node;
            last = node;
            node->next = node;
            node->pre = node;
        }else{
            last->next = node;
            first->pre = node;
            node->pre = last;
            node->next = first;
            last = last->next;
        }
    }
    return first;
}

//输出链表
void printTree(line *head,line *tail){
    while(head != tail->next){
        if(tail->isvalue == true)
            printf("%d ",tail->value);
        tail = tail->pre;
    }
}

//操作
int operation(line *&head, line *&tail){
    char s[10];
    scanf("%s",s);
    if(strcmp(s, "in") == 0){
        int value;
        scanf("%d",&value);
        if(head == tail->next){
            return 0;//队列满了放不下
        }else{
            head->value = value;
            head->isvalue = true;
            head = head->pre;
        }
        return 1;
    }else if(strcmp(s, "out") == 0){
        tail->isvalue = false;
        tail = tail->pre;
        return 1;
    }
    //下面为出错处理
    printf("%s指令错误,将输出当前队列\n",s);
    return -1;
}

int main(int argc, char* argv[])
{
    line *l = NULL;
    int size,opt;//空间大小,操作次数
    scanf("%d%d",&size,&opt);
    l = createNode(size);//l不能在使用,因为后面出队入队后,这个不能作为队尾或队头
    //声明队尾和队头
    line *head = l->pre, *tail = l->pre;
    while(opt--){
        //传的参数被函数修改(自查&的用法)
        int note = operation(head, tail);
        if(note == -1){
            break;
        }else if(note == 0)
            printf("队列已满!\n");
    }
    //打印队列
    printTree(head, tail);/////
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值