zoukankan      html  css  js  c++  java
  • 队列数组实现

    #include <stdio.h>
    #include <stdlib.h>
    #include <iostream>
    #include <string>
    #include <fstream>
    #include <vector>
    #include <list>
    #include <limits.h>
    #include <algorithm>
    
    /*队列数组实现*/
    struct Queue{
        int Capacity;//容量
        int Size;//实际大小
        int Front;//前指针
        int Rear;//后指针
        int* data;//数组
    };
    //1 is Empty
    int IsEmpty(Queue* q)
    {
        return q->Size == 0;
    }
    //1 is Full
    int IsFull(Queue* q)
    {
        return q->Capacity == q->Size;
    }
    //入队
    void Enqueue(Queue* q, int val)
    {
        if (IsFull(q))
        {
            printf("Queue is full!
    ");
            return;
        }
        q->Rear = (q->Rear + 1) % q->Capacity;
        q->data[q->Rear] = val;
        q->Size++;
    }
    //出队
    int Dequeue(Queue* q)
    {
        if (IsEmpty(q))
        {
            printf("Queue is Empty!
    ");
            return NULL;
        }
        int tmp = q->data[q->Front];
        q->Front = (q->Front + 1) % q->Capacity;
        q->Size--;
        return tmp;
    }
    //打印队列
    void PrintQueue(Queue* q)
    {
        if (IsEmpty(q))
        {
            printf("Queue is Empty!
    ");
            return;
        }
        int i = 0, j = q->Front;
        while (i < q->Size)
        {
            printf("%d
    ", q->data[j++%q->Capacity]);
            i++;
        }
        printf("
    ");
    }
    //创建队列
    Queue* CreateQueue(int MaxCapacity)
    {
        Queue* q = (Queue*)malloc(sizeof(Queue));
        q->Capacity = MaxCapacity;
        q->data = (int*)malloc(sizeof(int)*MaxCapacity);
        q->Front = 0;
        q->Rear = -1;
        q->Size = 0;
        return q;
    }
    
    
    int main(int argc,char** argv)
    {
        Queue *q=CreateQueue(5);
        Enqueue(q, 0);
        Enqueue(q, 1);
        Enqueue(q, 2);
        Enqueue(q, 3);
        Enqueue(q, 4);
        PrintQueue(q);
    
    
        Dequeue(q);
        Dequeue(q);
        PrintQueue(q);
    
        //Enqueue(q, 6);
        Enqueue(q, 7);
        Enqueue(q, 8);
        Enqueue(q, 9);
        PrintQueue(q);
        return 0;
    }
  • 相关阅读:
    37. Sudoku Solver(js)
    36. Valid Sudoku(js)
    35. Search Insert Position(js)
    34. Find First and Last Position of Element in Sorted Array(js)
    33. Search in Rotated Sorted Array(js)
    32. Longest Valid Parentheses(js)
    函数的柯里化
    俞敏洪:我和马云就差了8个字
    vue路由传值params和query的区别
    简述vuex的数据传递流程
  • 原文地址:https://www.cnblogs.com/wyc199288/p/5292007.html
Copyright © 2011-2022 走看看