简体   繁体   English

递归 function 以反转 Java 中队列的数组实现

[英]Recursive function to reverse an array implementation of a queue in Java

import java.util.Scanner;

class ed {
    int fr, r;
    int q[];
    int n;

    ed(int x) {
        n = x;
        fr = -1;
        r = -1;
        q = new int[n];
    }

    void enque(int n) {
        int val = n;
        while (r < n-1) {
            if (r==n-1) {
                System.out.println("Overflow");
                break;
            }
            else if (fr==-1 && r==-1) {
                fr=0;
                r=0;
                q[r] = val;
            }
            else {
                r += 1;
                q[r] = val;
            }
        }
    }
    void deque() {
        if (fr==-1 && r==-1) {
            System.out.println("Underflow");
        }
        else if (fr==r) {
            fr=-1;
            r=-1;
        }
        else {
            fr += 1;
        }
    }
    void reverse(int[] q) {
        int a = q[0];
        deque();
        reverse(q);
        enque(a);
    }
    void printq() {
        for (int i = fr; i<=r; i++) {
            System.out.print(q[i] + " ");
        }
    }
}

public class q1 {

    static Scanner f = new Scanner (System.in);
    public static void main(String[] args) {
        
        int n = f.nextInt();
        ed que = new ed(n);
        for (int i=0; i<n; i++) {
            int x = f.nextInt();
            que.enque(x);
        }
        // que.deque();

        // que.printq();
        que.reverse(que.q);

    }
}

My aim is to reverse a queue (Array) using a recursive function, but in VS Code, the loop is running infinite times and I'm not getting a chance to see the error.我的目标是使用递归 function 反转队列(数组),但在 VS Code 中,循环运行无限次,我没有机会看到错误。 I'd like to know my mistake, and any improvement is highly appreciated.我想知道我的错误,任何改进都非常感谢。 The class ed contains a constructor which initializes the array and the front, rear values. class ed 包含一个构造函数,用于初始化数组和前、后值。 Enque method adds an element to the queue at the rear, deque method removes the front element. enque 方法在队列后面添加一个元素,deque 方法删除前面的元素。 Reverse method takes an array input (queue), stores the foremost element in the variable a, deques it, calls itself, then enques it at the back. Reverse 方法接受一个数组输入(队列),将最前面的元素存储在变量 a 中,将其从队列中取出,调用自身,然后在后面将其入队。 VS Code is showing the error at line 48 (reverse(q), when it calls itself) but it's not showing the error as it's so far up. VS Code 在第 48 行显示错误(reverse(q),当它调用自身时)但它没有显示错误,因为它到目前为止。

A lot of things are not going the right way in your queue implementation using arrays.在使用 arrays 的队列实现中,很多事情都没有按照正确的方式进行。 Like, in enque function, you can fill values from rear = 0 to rear = n - 1 , because you have n positions available in the q array.就像,在 enque function 中,您可以将值从rear = 0填充到rear = n - 1 ,因为您在q数组中有n位置可用。

Your code was too long, unstructured, and a bit messy with no proper variable names, So, I didn't read it any further.你的代码太长,没有结构化,而且没有正确的变量名有点混乱,所以,我没有进一步阅读它。

But one thing I can make out is that you need to read how to implement a queue using the array .但我可以弄清楚的一件事是,您需要阅读如何使用数组实现队列

Now, coming to queue reversal using the recursion part.现在,使用递归部分来进行队列反转。 Your approach was correct, you just missed out the base case condition.您的方法是正确的,您只是错过了基本情况。

Steps for reversing queue:反转队列的步骤:

  1. Your queue has some elements, we get the first element out of the queue.您的队列有一些元素,我们从队列中取出第一个元素。
  2. Then, we assume I have a recursive function that reverses the rest of the queue.然后,我们假设我有一个递归的 function 反转队列的 rest。
  3. In this reversed queue, I just have to push that first element to the back.在这个反向队列中,我只需要将第一个元素推到后面。

And coming to the base case, each time queue size is decreasing by 1, so at the end, the queue will become empty then we don't have to do anything, just return.回到基本情况,每次队列大小减少 1,所以最后,队列将变为空,然后我们无需执行任何操作,只需返回即可。 THUS STOPPING THE RECURSION (which you missed).从而停止递归(你错过了)。

在此处输入图像描述

Here, is my implementation if you need some reference:如果您需要一些参考,这里是我的实现:

/*package whatever //do not write package name here */

import java.io.*;
import java.util.*;

class Queue {
    private int front, rear, capacity;
    private int queue[];
 
    Queue(int c) {
        front = rear = 0;
        capacity = c;
        queue = new int[capacity];
    }
    
    int size() {
        return rear - front;
    }
 
    void enqueue(int data) { 
        if (capacity == rear) {
            System.out.printf("Queue is full.\n");
            return;
        }
        else {
            queue[rear] = data;
            rear++;
        }
    }
 
    void dequeue() {
        if (front == rear) {
            System.out.printf("Queue is empty.\n");
            return;
        }
        else {
            for (int i = 0; i < rear - 1; i++) {
                queue[i] = queue[i + 1];
            }
            if (rear < capacity)
                queue[rear] = 0;
 
            rear--;
        }
    }
    
    int front() {
        if (front == rear) {
            System.out.printf("\nQueue is Empty.\n");
            return -1;
        }
        return queue[front];
    }
 
    void print() {
        int i;
        if (front == rear) {
            System.out.printf("Queue is Empty.\n");
            return;
        }
 
        for (i = front; i < rear; i++) {
            System.out.printf(" %d, ", queue[i]);
        }
        System.out.println("");
        return;
    }
}


class GFG {
    static Scanner scanner = new Scanner(System.in);
    
    public static void reverseQueue(Queue queue) {
        if (queue.size() == 0) {
            return;
        }
        
        int frontElement = queue.front();
        queue.dequeue();
        reverseQueue(queue);
        queue.enqueue(frontElement);
    }
    
    public static void main (String[] args) {
        int queueSize = scanner.nextInt();
        
        Queue queue = new Queue(queueSize);
        for (int i = 0; i < queueSize; i++) {
            int element = scanner.nextInt();
            queue.enqueue(element);
        }
        
        queue.print();
        reverseQueue(queue);
        queue.print();
    }
}

You can comment if anything is wrong, or need more clarification.如果有任何问题或需要更多说明,您可以发表评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM