I'm studying mobile Q, but there's something I don't understand (indicated by <--)

Asked 2 years ago, Updated 2 years ago, 105 views

#include <stdio.h>
int a[4];
int front = -1;
int rear = -1;

void enQueue(int in)
{

    int i, j;
    If (ear < 3) { // <----Why should it be less than part 3 here?

``      ``      rear++;
        a[rear] = in;
        printf("a[%d] = %d \n", rear, a[rear]);

    }
    else if (rear == 3 && front==-1) 
``{

        printf("Full".\n");

    }
    else if (rear == 3 && front > -1)
``{

        for (i = front + 1, j = 0; i < 4; i++, j++) {
            a[j] = a[i];

        }

        Rear = 4 - front - 1; //<---- Why is the transplant?
        front = -1;
        printf ("Move Forward\n");
        a[rear] = in;
        printf("a[%d] = %d \n", rear, a[rear]);

    }  




}

int deQueue()
{

    int out;

    if (front == rear) {
        printf ("No more subtraction values found.\n");
        rear = -1, front = -1;
        return 0;
    }
    else {
        front++;
        out = a[front];
        printf("a[%d] = %d \n", front, out);
        return out;
    }

}

int main() {

    int inQ;
    int outQ;

    int select;

    while (1) {
        printf ("EnQueue 1 and EnQueue 2 and deQueue 3");
        scanf_s("%d", &select);

        switch (select)
        {
        case 1:
            scanf_s("%d", &inQ);
            enQueue(inQ);
            break;
        case 2:
            outQ = deQueue();
            break;
        case 3:
            return 0;
            break;



        }

    }

}

queue c++

2022-09-20 15:57

1 Answers

if (ear < 3) { // <--- Why should it be less than part 3 here?

The size of the array a in the top row is 4. Rear is a variable that represents the index of the most recent data that has been queued. a Since the array size is 4, the maximum index is 3. Therefore, if (rear < 3) means that the rear is not yet 3; that is, if the array is not yet full.

are = 4-front-1; //<-- Why is the transplant coming out?

Rear is the variable that represents the index of the recently entered data Front+1 is the variable that represents the index of the data entered the longest time.

The expression that I just asked is that the rear moved to the end of the array, and instead, when there's an empty space in the front of the array, the for loop right above is used to copy all of the data to the left of the array.

I copied all the data, so I need to change the front and rear values. You can initialize the front to -1 Rear was 3 when the data was tightly located, and the oldest data position before starting copying was front+1. Therefore, move the rear to a position of 3-(front+1), increase the rear value by 1 and insert the new data in the increased position. If you write this process in two lines,

rear=3-(front+1);
++rear;

Summarize the above two lines into one line

rear = 4-front-1;

That's what I said.


2022-09-20 15:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.