C language-simple implementation of cyclic queues

Source: Internet
Author: User

It is not difficult to implement a loop queue in C language. The key point is to judge the queue "empty" and "full" status.

As described in the C and pointers, there are two ways to make judgments about the queue's empty and full state. In the array hollow an element is not filled in, at the beginning, the set tail is 0, front is 1, thus, the realization to waste queue buffer two element space: Queue null: (tail+1)% Queue_size = = Front Queue full: (tail+2)% q Ueue_size = = Front defines a variable to record the number of elements in the queue, to determine the queue's empty and full directly look at the value of the variable

The 2nd type is used in this article:

#include <stdio.h>

#define QUEUE_SIZE          5
#define QUEUE_TYPE          int

static int queue_cnt = 0;
static int queue_front = 0;
static int queue_tail = 0;

Static Queue_type queue_buf[queue_size];

int Is_empty ()
{return
    queue_cnt = = 0;
}

int Is_full ()
{return
    queue_cnt = = queue_size;
}

int Insert (Queue_type e)
{
    if (Is_full ()) {
        printf ("QUEUE is full!!! \ n ");
        return 0;
    }
    Queue_buf[queue_tail] = e;
    Queue_tail = (queue_tail + 1)% Queue_size;
    queue_cnt++;

    return 1;
}

int delete ()
{
    if (Is_empty ()) {
        printf ("Queue is empty!!! \ n ");
        return 0;
    }
    Queue_front = (queue_front + 1)% Queue_size;
    queue_cnt--;
    return 1;
}

int main ()
{
    insert (3);
    Insert (3);
    Insert (3);
    Insert (3);
    Insert (3);
    Delete ();
    Insert (3);
    Insert (3);
    return 0;
}



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.