循环队列,队链的实现

总体来说实现起来和栈是差不多的,都是操作受限的顺序表。进行一点特殊处理就行了。

循环队列:

#include<iostream>
#include<ctime>
#include<cstdlib>
#define MAX 1001
using namespace std;
typedef struct {
    int a[MAX];
    int front,rear;
}SQueue;

void Init(SQueue *s)
{
    s->front=0;
    s->rear=0;
}
bool Insert(SQueue *s,int e)
{
    if(s->front==s->rear+1)
        return false;
    s->a[s->rear]=e;
    s->rear++;
    s->rear%=MAX;
    return true;
}
bool Delete(SQueue *s,int *e)
{
    if(s->rear==s->front)
        return false;
    *e=s->a[s->front];
    s->front++;
    s->front%=MAX;  //point
    return true;
}
int SQueuelenth(SQueue s)
{
    int len=0;
    if(s.front>=s.rear)
        len=s.front-s.rear;
    else
        len=s.rear-s.front;
    return len;
}
int main()
{
    srand(time(NULL));
    SQueue s;
    Init(&s);
    int n=rand()%20;
    cout<<"n="<<n<<endl;
    for(int i=0;i<n;++i){
        int e=rand()%10;
        if(Insert(&s,e))
            cout<<e<<" ";
        else
            cout<<"ERROR ";
    }
    cout<<endl;
    int len=SQueuelenth(s);
    cout<<"len= "<<len<<endl;
    int *e;
    if(Delete(&s,e))
        cout<<"e="<<*e<<endl;
    else
        cout<<"Delete Error"<<endl;
    len=SQueuelenth(s);
    cout<<"len="<<len<<endl;
    return 0;
}

队链:

#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;

typedef struct Node{
    int e;
    Node *next;
}Queue;
Queue *Init()
{
    return (Queue*)malloc(sizeof(Queue));
}
Queue* Insert(Queue *s,int e)
{
    s->next=(Queue*)malloc(sizeof(Queue));
    s=s->next;
    s->e=e;
    s->next=NULL;
    cout<<s->e<<" ";
    return s;
}
int QueueLen(Queue *s)
{
    int count=0;
    Queue *p=s;
    while(p->next!=NULL)
    {
        count++;
        p=p->next;
    }
    return count;
}
Queue* DeleteQueue(Queue *s)
{
    Queue *p=s;
    s=s->next;
    int e=s->e;
    free(p);
    cout<<"e="<<e<<endl;
    return s;
}
int main()
{
    srand(time(NULL));
    Queue *head,*rear;
    head=rear=Init();
    int n=rand()%20;
    cout<<"n="<<n<<endl;
    for(int i=0;i<n;++i){
        int e=rand()%10;
        rear=Insert(rear,e);
    }
    cout<<endl;
    int len=QueueLen(head);
    cout<<"len="<<len<<endl;
    head=DeleteQueue(head);
    len=QueueLen(head);
    cout<<"len="<<len<<endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值