队列实现,入队方法不起作用 [英] Queue implementation, enqueue method not working

查看:45
本文介绍了队列实现,入队方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写自己的队列类.我的入队方法只是将一个对象入队,然后如果我尝试将其他任何对象入队,几乎就像忽略它一样.这是我的代码:

I am trying to write my own queue class. My enqueue method is only enqueue-ing one object and then if I try to enqueue anything else, its almost as if its ignoring it. Here is my code:

public class myQueue {

    private Node front;
    private Node back;
    private int s;

    public myQueue() {
            front = null;
            back = null;
            s = 0;
    }

    public void enqueue(Object x) {
        if( isEmpty() )
            back = front = new Node(x);
        else
            back = back.next = new Node(x);
        s++;
    }

    public Object dequeue() {
        Object x;
        if( isEmpty() ) { System.out.println("nothing to dequeue.\nqueue empty."); }
        x = front.data;
        s--;
        return x;
    }

    public boolean isEmpty() {
        if(s == 0)
            return true;
        else
            return false;
    }

    public void printQueue() {
        if ( isEmpty() )
            System.out.println("empty queue");
        else {
            Node temp = back;
            while(temp != null) {
                System.out.println(temp);
                temp = temp.next;
            }
        }   
    }



}

这是我尝试将一些对象入队的主要方法:

and here is my main method where i try to enqueue some objects:

public static void main(String[] args) {
    int a = 5;
    String b = "yo";
    Object c = 5.5;                
    int d = 2;
    String e = "Pen";
    Object f = 9.2;

    myQueue q = new myQueue();

    q.enqueue(a);
    q.enqueue(b);
    q.enqueue(c);
    q.enqueue(d);
    q.enqueue(e);
    q.enqueue(f);

    System.out.println("\n");

    q.printQueue();
}

然后我得到的输出是:

数据:9.2

关于为什么会发生这种情况的任何想法?

any ideas as to why this is happening?

推荐答案

打印时,你是从队列的后面开始,你应该从前面开始:

When you print, you are starting at the back of the queue, you should start at the front:

        Node temp = front; // <<< replacing back by front
        while(temp != null) {
            System.out.println(temp);
            temp = temp.next;
        }

如果你从队列的后面开始,你将只打印队列的最后一个元素...

If you start at the back of the queue, you will only have the last element of the queue to be printed...

我的修复结果:

data : 5
data : yo
data : 5.5
data : 2
data : Pen
data : 9.2

这篇关于队列实现,入队方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆