将循环双链表的代码转换为普通双链表的代码,只需要修改一些与循环相关的部分即可。以下是将代码进行修改后的结果:
package dataStructure;
public class DoublyList<T> {
public DoubleNode<T> head;
public DoublyList() {
this.head = null;
}
public boolean isEmpty() {
return head == null;
}
public String toString() {
if (isEmpty()) {
return "Empty List";
}
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getName()).append("(");
DoubleNode<T> p = head;
while (p != null) {
sb.append(p.data.toString());
if (p.next != null) {
sb.append(",");
}
p = p.next;
}
sb.append(")");
return sb.toString();
}
public DoubleNode<T> insert(int i, T x) {
if (x == null || i < 0) {
return null;
}
if (i == 0) { // 插入到头结点之前
DoubleNode<T> q = new DoubleNode<>(x, null, head);
if (head != null) {
head.prev = q;
}
head = q;
return q;
}
DoubleNode<T> front = getNode(i - 1); // 获取前一个节点
if(front==null){
return null;
}
DoubleNode<T> newNode=new DoubleNode<>(x,null,null);
newNode.next=front.next;
newNode.prev=front;
if(front.next!=null){
front.next.prev=newNode;
}
front.next=newNode;
return newNode;
}
public DoubleNode<T> insert(T x) {
if (x == null) {
return null;
}
DoubleNode<T> newNode = new DoubleNode<>(x, null, head);
if (head != null) {
head.prev = newNode;
}
head = newNode;
return newNode;
}
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 void addAll(DoublyList<T> list) {
for(DoubleNode<T> p=list.head;p!=null;p=p.next){
insert(p.data);
}
}
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());
list1.addAll(list2);
System.out.println(list1.toString());
}
}
上述代码是将循环双链表的部分修改为普通双链表的代码,实现了插入、遍历和合并两个双链表的功能。
内容由零声教学AI助手提供,问题来源于学员提问




