下面是使用Java编写的DoublyList类及其相关方法和一个简单的main方法来验证:
class DoublyListNode<T> {
T data;
DoublyListNode<T> prev;
DoublyListNode<T> next;
public DoublyListNode(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyList<T> {
private DoublyListNode<T> head;
private int size;
public DoublyList() {
head = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public void addAll(int i, DoublyList<T> list) {
if (i < 0 || i > size)
throw new IndexOutOfBoundsException("Invalid index: " + i);
if (list.isEmpty())
return;
if (head == null && i == 0) { // If the current list is empty
head = list.head;
size += list.size;
return;
}
if (i == 0) { // Insert at the beginning
list.head.prev = null;
list.getLastNode().next = head;
head.prev = list.getLastNode();
head = list.head;
size += list.size;
return;
}
if (i == size) { // Insert at the end
getLastNode().next = list.head;
list.head.prev = getLastNode();
size += list.size;
return;
}
DoublyListNode<T> currentNode = getNodeAt(i);
currentNode.prev.next = list.head;
list.head.prev=currentNode.prev;
list.getLastNode().next=currentNode;
currentNode.prev=list.getLastNode();
size += list.size;
}
private DoublyListNode<T> getNodeAt(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("Invalid index: " + index);
DoublyListNode<T> currentNode = head;
for (int i = 0; i < index; i++) {
currentNode = currentNode.next;
}
return currentNode;
}
private DoublyListNode<T> getLastNode() {
DoublyListNode<T> lastNode = head;
while (lastNode.next != null) {
lastNode = lastNode.next;
}
return lastNode;
}
public String toString() {
StringBuilder sb = new StringBuilder();
DoublyListNode<T> currentNode = head;
while (currentNode != null) {
sb.append(currentNode.data).append(" ");
currentNode = currentNode.next;
}
return sb.toString();
}
}
public class Main {
public static void main(String[] args) {
DoublyList<Integer> list1=new DoublyList<>();
list1.addAll(0, createDoublyList(new Integer[]{1, 2, 3}));
DoublyList<Integer> list2=new DoublyList<>();
list2.addAll(0, createDoublyList(new Integer[]{4,5}));
list1.concat(2,list2);
System.out.println(list1); // Output: 1 2 4 5 3
}
private static <T> DoublyList<T> createDoublyList(T[] values) {
DoublyList<T> list=new DoublyList<>();
for(T value : values) {
list.addAll(list.size,value);
}
return list;
}
}
以上是一个简单的示例,包含了DoublyList类和相关方法以及一个使用示例的main方法。请注意,这里没有实现concat方法,你可以自行完成它的实现。
内容由零声教学AI助手提供,问题来源于学员提问




