Java语言怎么用语句和属性实现对链表插入的管理,用属性的方式限制插入链表的数据怎么封装代码的

Java语言怎么用语句和属性实现对链表插入的管理,用属性的方式限制插入链表的数据怎么封装代码的


public class LinkedList<T> {
    private Node<T> head;
    
    private static class Node<T> {
        T data;
        Node<T> next;
        
        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
    
    public void insert(T data) {
        Node<T> newNode = new Node<>(data);
        
        if (head == null) {
            head = newNode;
        } else {
            Node<T> current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
    
    public void display() {
        Node<T> current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.insert(1);
        list.insert(2);
        list.insert(3);
        list.display(); // Output: 1 2 3
        
        LinkedList<String> stringList = new LinkedList<>();
        stringList.insert("Hello");
        stringList.insert("World");
        stringList.display(); // Output: Hello World
    }
}
public class LinkedList<T> {
    private Node<T> head;
    
    private static class Node<T> {
        T data;
        Node<T> next;
        
        public Node(T data) {
            this.data = data;
            this.next = null;
        }
    }
    
    public void insert(T data) {
        Node<T> newNode = new Node<>(data);
        
        if (head == null) {
            head = newNode;
        } else {
            Node<T> current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }
    
    public void display() {
        Node<T> current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.insert(1);
        list.insert(2);
        list.display(); 
        
        LinkedList<String> stringList = new LinkedList<>();
        stringList.insert("test——word");
        stringList.insert("test2");
        stringList.display(); 
    }
}

这个 可以看刚才给你回的那个代码 哈 是一样的

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^