java - 通用链表删除、大小、获取方法

标签 java generics linked-list

我刚刚在 Stackoverflow 上的“Java 中的通用链接列表”问题中看到了这段精彩的代码。我在想如何实现方法remove(从链表中删除单个节点),size(获取列表的大小)和get(获取a节点)。有人可以告诉我该怎么做吗?

public class LinkedList<E> {
private Node head = null;

private class Node {
    E value;
    Node next;

    // Node constructor links the node as a new head
    Node(E value) {
        this.value = value;
        this.next = head;//Getting error here
        head = this;//Getting error here
    }
}

public void add(E e) {
    new Node(e);
}

public void dump() {
    for (Node n = head; n != null; n = n.next)
        System.out.print(n.value + " ");
}

public static void main(String[] args) {
    LinkedList<String> list = new LinkedList<String>();
    list.add("world");
    list.add("Hello");
    list.dump();
}

}

最佳答案

用于操作 remove()size()contains() 的 LinkedList 实现 看起来像这样:

static class LinkedList<Value extends Comparable> {

        private Node head = null;
        private int size;

        private class Node {
            Value val;
            Node next;

            Node(Value val) {
                this.val = val;
            }
        }

        public void add(Value val) {
            Node oldHead = head;
            head = new Node(val);
            head.next = oldHead;
            size++;
        }

        public void dump() {
            for (Node n = head; n != null; n = n.next)
                System.out.print(n.val + " ");
            System.out.println();
        }

        public int size() {
            return size;
        }

        public boolean contains(Value val) {
            for (Node n = head; n != null; n = n.next)
                if (n.val.compareTo(val) == 0)
                    return true;
            return false;
        }

        public void remove(Value val) {
            if (head == null) return;
            if (head.val.compareTo(val) == 0) {
                head = head.next;
                size--;
                return;
            }

            Node current = head;
            Node prev = head;
            while (current != null) {
                if (current.val.compareTo(val) == 0) {
                    prev.next = current.next;
                    size--;
                    break;
                }
                prev = current;
                current = current.next;
            }
        }
    }

关于java - 通用链表删除、大小、获取方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61621541/

相关文章:

c++ - 替代标准命名空间中的嵌套映射

c - 我第一次使用链表。想要一些关于如何解决某些问题的批评和建议

javax.mail.NoSuchProviderException : Invalid protocol :null

java - JdbcTemplate查询,是什么?

java - Collectors.summingInt() 与 mapToInt().sum()

c# - 为什么不能为泛型类型推断类型参数?

spring - 嵌套具体化参数无法创建 ParameterizedTypeReference

java - 具体类作为通用参数

.net - LinkedList 中的 Foreach Item 是否按顺序给出项目?

java - 二叉树问题。检查相似的形状