ZBLOG

public class CirDoublyList { public DoubleNode head; public DoubleNode rear; public CirDoublyList() { this.head=new DoubleNode(); this.head.prev=this.head; this.head.next=this.head; } publi...

以下是修改后的代码:

public class CirDoublyList<T> {
    public DoubleNode<T> head;
    public DoubleNode<T> rear;

    public CirDoublyList() {
        this.head = new DoubleNode<>();
        this.head.prev = this.head;
        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(T x) {
        if (x == null)
            return null;
        DoubleNode<T> q = new DoubleNode<>(x, head.prev, head);
        head.prev.next = q;
        head.prev = q;
        return q;
    }

    public void concat(CirDoublyList<T> list) {
        DoubleNode<T> rear = this.head;
        while (rear.next != this.head)
            rear = rear.next;

        rear.next = list.head.next;
        list.head.next.prev = rear;

        rear = list.head;
        
         // 恢复list的空表状态
         list.head.prev = list.head;
         list.head.next= list.head;

         // 将rear指向当前链表尾节点
         while (rear.next != rear)
             rear=rear.next; 
             
         // 连接原链表尾和新链表头  
          rear.next=this.head; 
          this.rear=rear;//更新尾节点
        
   }

    public void addAll(CirDoublyList<T> list) {
       concat(list);
     }

    public CirDoublyList<T> union(DoublyList<T> list) {
        CirDoublyList<T> result = new CirDoublyList<>(this);
        result.addAll(list);
        return result;
    }

    public static void main(String[] args) {
        CirDoublyList<Integer> list1 = new CirDoublyList<>();
        DoublyList<Integer> list2 = new DoublyList<>();
        for (int i = 1; i <= 5; i++)
            list1.insert(i);
        for (int i = 6; i <= 10; i++)
            list2.insert(i);
        System.out.println(list1.toString());
        System.out.println(list2.toString());
        list1.addAll(list2);
        System.out.println(list1.toString());
    }
}

在上面的代码中,我们为循环双链表类添加了 concataddAllunion 方法。其中:

  • concat 方法将另一个循环双链表连接到当前链表的末尾,并更新尾节点。
  • addAll 方法是 concat 的别名,将另一个循环双链表连接到当前链表的末尾,并更新尾节点。
  • union 方法返回两个链表的并集,在原有链表基础上添加新的元素。

希望以上修改满足你的需求。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=8799

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?