你已经提供了一个使用泛型的双链表类,我可以帮助你做出一些修改来适应双链表的需求。以下是修改后的代码:
public class DoublyList<T> {
public DoubleNode<T> head;
public DoublyList() {
this.head = new DoubleNode<>();
this.head.prev = this.head;
this.head.next = this.head;
}
public boolean isEmpty() {
return this.head.next == this.head;
}
public String toString() {
String str = this.getClass().getName() + "(";
for (DoubleNode<T> p = this.head.next; p != this.head; p = p.next)
str += p.data.toString() + ((p.next != this.head) ? "," : "");
return str + ")";
}
public DoubleNode<T> insert(int i, T x) {
if (x == null)
return null;
DoubleNode<T> front = getNode(i - 1);
if (front == null)
front = head;
DoubleNode<T> q = new DoubleNode<>(x, front, front.next);
front.next.prev = q;
front.next = q;
return q;
}
public void insert(T x) {
if (x == null)
return;
DoubleNode<T> q = new DoubleNode<>(x, head.prev, head);
head.prev.next = q;
head.prev = q;
}
private DoubleNode<T> getNode(int index) {
if(index < 0 || index >= size())
return null;
DoubleNode<T> current = head.next;
for(int i=0; i<index; i++)
current=current.next;
return current;
}
public void addAll(DoublyList<T> list) {
if (list == null)
return;
for (DoubleNode<T> p = list.head.next; p != list.head; p = p.next)
insert(p.data);
}
public int size() {
int count = 0;
for (DoubleNode<T> p = this.head.next; p != this.head; p = p.next)
count++;
return count;
}
public static void main(String[] args) {
DoublyList<Integer> list1 = new DoublyList<>();
DoublyList<Integer> list2 = new DoublyList<>();
for(int i=6; i<=10; i++)
list1.insert(i);
for(int i=11; i<=15; i++)
list2.insert(i);
System.out.println("List 1: " + list1.toString());
System.out.println("List 2: " + list2.toString());
list1.addAll(list2);
System.out.println("Combined List: " + list1.toString());
}
}
这里对代码进行了一些修改和调整,添加了 getNode 方法来获取指定索引位置的节点,并在 insert 方法中使用它。还增加了 size 方法来返回链表的大小。
内容由零声教学AI助手提供,问题来源于学员提问




