【问题标题】:What is the error in the following Queue implementation using linked list?以下使用链表的队列实现中的错误是什么?
【发布时间】:2015-08-15 10:51:09
【问题描述】:

我使用不维护对尾节点的引用的链表编写了队列的以下实现。当我尝试打印队列时,它只输出头部,即只输出一个节点。错误是什么?提前致谢!

package DataStructures;

import java.util.Scanner;

class Node {
    int x;
    Node nextNode;

    public Node(int x) {
        this.x = x;
        nextNode = null;
    }
}

class Queue {
    Node head = null;
    int n = 0;

    public void enqueue(int x) {
        if (n==0){
            head = new Node(x);
            n++;
            return;
        }
        Node tempHead = head;
        while (tempHead != null){
            tempHead = tempHead.nextNode;
        }
        tempHead = new Node(x);
        tempHead.nextNode = null;
        n++;
    }

    public int dequeue() {
        if (head == null) {
            throw new Error("Queue under flow Error!");
        } else {
            int x = head.x;
            head = head.nextNode;
            return x;
        }
    }

    public void printTheQueue() {
        Node tempNode = head;
        System.out.println("hi");
        while (tempNode != null){
            System.out.print(tempNode.x + "  ");
            tempNode = tempNode.nextNode;
        }

    }

}

public class QueueTest {

    private static Scanner in = new Scanner(System.in);

    public static void main(String[] args) {
        Queue queue = new Queue();
        while (true){
            int x = in.nextInt();
            if (x == -1){
                break;
            } else{
                queue.enqueue(x);
            }
        }

        queue.printTheQueue();
    }

}

【问题讨论】:

  • 当您入队时,head 和您的新节点之间没有任何连接。
  • @RealSkeptic 但我确实有一个对 head 的临时引用并通过它传播以到达最后一个节点。到达最后一个节点后,我将其 nextNode 指向具有数据键 x 的新节点。

标签: java linked-list queue


【解决方案1】:

您永远不会将节点分配给 nextNode,因此您的列表要么是空的,要么由一个节点组成。

这里有一个解决方案:

public void enqueue(int x) {
    n++;
    if (head == null) {
        head = new Node(x);
    else {
        Node last = head;
        while (last.nextNode != null)
            last = last.nextNode;
        last.nextNode = new Node(x);
    }
}

从技术上讲,您不需要n,但您可以将其用作列表大小的缓存。你应该在deque() 中减少它。

【讨论】:

  • 如果您能告诉我代码中的更改应该是什么,我将不胜感激
  • Thanx...明白了...我正在将 new Node() 分配给 tempHead,这是一个飞行参考。相反,我应该使用适当的逻辑将 new Node() 分配给 tempHead.nextNode! !!
  • n++ 应该出现在方法的末尾。
【解决方案2】:

让你加入这个队列:

public void enqueue(int x) {
 if (n==0){
        head = new Node(x);
        head.nextNode=null;
        n++;
        return;
    }
    Node tempHead = head;
    while (tempHead.nextNode!= null){
        tempHead = tempHead.nextNode;
    }
    Node newNode = new Node(x);
    tempHead.nextNode=newNode;
    newNode.nextNode = null;
    n++;
}

【讨论】:

  • 是的,它是正确的!......但是如果我删除 if 语句 if(n==0),你的代码会崩溃,因为 head 为空并且我们正在访问它的 nextNode... . 你能提供一个提示吗??
猜你喜欢
  • 1970-01-01
  • 2016-07-02
  • 1970-01-01
  • 2012-05-15
  • 2018-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-17
相关资源
最近更新 更多