简体   繁体   English

如何在确保最后一个元素指向第一个元素的同时将其排入圆形链表?

[英]How do I enqueue to a circular linked list while making sure that the last element points to the first?

I'm trying to build an enqueue method for a circular linked list. 我正在尝试为循环链表建立一个enqueue方法。 Here is what I am have so far: 这是我到目前为止所拥有的:

public class Test<T> implements UnboundedQueueInterface<T> {
    protected LLNode<T> rear;
    protected LLNode<T> current;

    public Test() {
        rear = null;
        current = null;
    }

    @Override
    public boolean isEmpty() {
        if (rear == null) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void enqueue(T element) {
        LLNode<T> node = new LLNode<T>(element);

        if (rear == null) {
            rear = node;
            node.setLink(rear);
        } else {
            LLNode<T> temp = rear;
            rear = node;
            node.setLink(temp);
        }
    }
}

Instead of the last element linking to the first, it links to the second to last and so forth. 而不是链接到第一个元素的最后一个元素,它链接到倒数第二个,依此类推。 Any ideas? 有任何想法吗?

LLNode<T> temp = rear;
rear = node;
node.setLink(temp);

temp holds the original rear. temp保持原来的后方。 When you call setLink, you are saying to point to temp, which is the original rear. 当你调用setLink时,你要指的是temp,这是原来的后方。 Instead, you need to point to rear.getLink() to point to the first element (since the old rear was pointing to the first element). 相反,您需要指向rear.getLink()指向第一个元素(因为旧的后部指向第一个元素)。

After that, you still have another link to fix. 之后,您还有另一个要修复的链接。 temp (the old rear) is still pointing to the first element, but it should be updated. temp(旧的后部)仍指向第一个元素,但应该更新。

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

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