修改循环双链表代码为双链表代码,不进行增加或减少方法,尽量保持原有结构,如下所示:
public class DoublyList<T> {
public DoubleNode<T> head;
public DoublyList() {
this.head = null;
}
public boolean isEmpty() {
return head == null;
}
public String toString() {
String str = this.getClass().getName() + "(";
for (DoubleNode<T> p = this.head; p != null; p = p.next)
str += p.data.toString() + ((p.next != null) ? "," : "");
return str + ")";
}
public DoubleNode<T> insert(int i, T x) {
if (x == null || i < 0)
return null;
if (i == 0) { // 在链表头部插入
DoubleNode<T> q = new DoubleNode<T>(x, null, head);
if (head != null)
head.prev = q;
head = q;
return q;
}
DoubleNode<T> front = getNode(i - 1); // 获取第i-1个节点
if (front == null) // i超出范围
return null;
DoubleNode<T> q = new DoubleNode<>(x, front, front.next);
if(front.next !=null) // 插入位置非尾部节点
front.next.prev=q;
front.next=q;
return q;
}
public DoubleNode<T> insert(T x) {
return insert(size(), x); // 调用insert方法,在末尾插入元素
}
private DoubleNode<T> getNode(int i) {
if (i >= 0) {
DoubleNode<T> p = head;
for (int j = 0; p != null && j < i; j++)
p = p.next;
return p;
}
return null;
}
public int size() {
int count = 0;
for (DoubleNode<T> p = head; p != null; 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(list1.toString());
System.out.println(list2.toString());
// 合并两个双链表
DoublyList<Integer> newList = new DoublyList<>();
// 将list1的元素插入newList
for(DoubleNode<Integer> p=list1.head;p!=null;p=p.next)
newList.insert(p.data);
// 将list2的元素插入newList
for(DoubleNode<Integer> q=list2.head;q!=null;q=q.next)
newList.insert(q.data);
System.out.println(newList.toString());
}
}
请注意,上述代码只是将循环双链表改为了双链表,并且添加了合并两个双链表的逻辑。其他方法没有进行增加或删除。
内容由零声教学AI助手提供,问题来源于学员提问




