循环队列,队链的实现

    xiaoxiao2021-03-25  94

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

    循环队列:

    #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() ; cout<<"n="<<n<<endl; for(int i=0;i<n;++i){ int e=rand(); 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; }
    转载请注明原文地址: https://ju.6miu.com/read-24384.html

    最新回复(0)