繁体   English   中英

如何在循环单链接列表中实现“删除”和“搜索”?

[英]How can you implement Delete and Search in a circular singly linked list?

我正在尝试实现delete(Node x)方法和search(E key)方法,但是我不明白如何制作遍历列表的循环? 我尝试编写删除方法。 到目前为止,这是我的代码:

public class CircularSinglyLinkedList<E> {

    private Node<E> head;
    private Node<E> tail;

    private class Node<E> {
        public final E key;
        public Node<E> next;

        private Node(E key) {
            this.key = key;
        }
    }

    public void insert(Node<E> x) {
        x.next = head;
        tail.next = x;
        head = x;
    }

    public void delete(Node<E> x) {
        Node<E> y = head;
        while(y != x && y.next != head) {
            y = y.next;
        }
        if(y.next == x) {
            y.next = x.next;
            x.next = null;
        }
    }

    public E search(E key) {

    }

}

您将需要遍历循环列表以删除和搜索节点。 我希望以下代码会有所帮助:

private Node delete(Node x) {
    Node node = head;
    do {
        if (node.next.element == x.element) {
            Node n = node.next;
            node.next = n.next;
            if (n == head) { // removal of head
                head = node;
            }
            return n;
        }
        node = node.next();
    } while(node != head);
    return null;
}

它将搜索节点x并将其删除。 尽管您尚未发布Node类的结构,但我仍然希望您可以进行相关更改。

该函数将拒绝删除最后一个元素(当列表仅包含一个元素时),因为在循环链接列表中,我认为最后一个元素的下一个元素为首。

我想,您需要做的就是将循环转换为后条件循环,就像这样:

Node<E> y = head;
do {
    if (y.next == x) {
        y.next = x.next;
        x.next = null;
        return;
    }
    y = y.next;
} while (y != head);

最好在您的search方法中实现节点搜索(使其返回Node<E> )。

顺便说一句, delete方法将Node<E>作为参数,但是很难从外部调用它,因为调用者无法从任何地方获取对Node<E>引用: headtail是私有的,并且search返回E ,不是Node<E>

您需要在Node类中实现equalshashCode方法。

while(!y.equals(x) && !y.next.equals(head)) {
    y = y.next;
}

暂无
暂无

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

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