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();
}
}
这个 可以看刚才给你回的那个代码 哈 是一样的
不知道你这个问题是否已经解决, 如果还没有解决的话:在第一个数组内部,定义一个布尔类型的变量,如果在进入循环的时候,把结构设置为true,也就是第一次排序后,没有任何移动的话,那么数组布尔就不会变成false