java - java实现循环链​​表

标签 java circular-list

我在实现循环链表时遇到了一些问题。我正在处理一个需要您自己实现任何 ADT 的问题。我似乎可以在列表中添加节点,但是在删除时我不熟悉。我包含了前两个删除方法,让您了解我的想法,我将如何删除列表中的最后一个节点?

public class LinkedList {
    private Node head;
    private Node tail;
    private int size = 0;
    LinkedList() {
        head = null;
        current = null;
        previous = null;
        tail = null;
        size = 0;
    }

    //checks if list is empty
    public boolean isEmpty() {
        return head == null;
    }
    //add new node to front of circularly linked list
    public void addToFront(E x) {
        if (head == null) {
            head = new Node(x);
        } else {
            Node n = new Node(x);
            x.next() = head;
            head = x;
        }
    }

    public void addtoMiddle(E x) {
        x.next = current.next();
        current.next = x;
        size = size + 1;
    }

    public void addToEnd(E x) {
        x.next = null;
        tail.next() = x;
        tail = x;
        size = size + 1;
    }

    public void removeFirst(E x) {
        if (head = null) {
            System.out.println("Error! List is empty!");
        } else {
            head = current.next();
            size = size + 1;
        }
    }

    public void removeMiddle(E x) {
        previous.next() = current.next();
        current.next() = null;
        size = size + 1;
    }

最佳答案

在循环链表中,最后一个节点的 next 指向头部,因此您循环遍历节点直到 node.next.equals( head )。请注意,next 绝不能为 null,如果您只有一个节点,则您有 head.next = head

在循环双向链表中,您还有一个 previous 节点,即您可以向后迭代。在这种情况下,您的最后一个节点只是 head.previous

一个小的ascii图片:

head -next---> node -next---> node -next---> last
 | ^  <---prev-      <---prev-      <---prev- | ^
 | |                                          | |
 | |_____________________________________next_| |
 |_prev_________________________________________|      

关于java - java实现循环链​​表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32867682/

相关文章:

java - 在哪里可以下载 JBoss Developer Studio 2.0 GA?

java - Multi-Tenancy Web 应用程序的性能监控工具

c++ - bool 运算符缺少模板参数?

C 链表插入函数在末尾创建不需要的条目

Windows Server 2012 上的 JavaService.exe

java - postgresql 驱动程序 9.4 和 Postgres 安装 9.6 的 UTF-8 序列无效

java - 如何使用 JNA 读取 Linux 命令的输出

c - 减少C中链表遍历时的迭代次数

android - 如何在 Android 主屏幕的角落滑动启动应用程序,或者它可能是任何屏幕,如惰性滑动

java - 将两个类(class)合二为一