循环队列,队链的实现

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

循环队列:

#include
#include
#include
#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="<for(int i=0;iint e=rand()%10;
        if(Insert(&s,e))
            cout<" ";
        else
            cout<<"ERROR ";
    }
    cout<int len=SQueuelenth(s);
    cout<<"len= "<int *e;
    if(Delete(&s,e))
        cout<<"e="<<*e<else
        cout<<"Delete Error"<cout<<"len="<return 0;
}

队链:

#include
#include
#include
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="<return s;
}
int main()
{
    srand(time(NULL));
    Queue *head,*rear;
    head=rear=Init();
    int n=rand()%20;
    cout<<"n="<for(int i=0;iint e=rand()%10;
        rear=Insert(rear,e);
    }
    cout<int len=QueueLen(head);
    cout<<"len="<"len="<return 0;
}

你可能感兴趣的:(Queue)