ZBLOG

public class DoublyList1 { public DoubleNode head; public DoublyList1() { this.head=new DoubleNode(); this.head.prev=this.head; this.head.next=this.head; } public boolean isEmpty() { ...

你已经提供了一个使用泛型的双链表类,我可以帮助你做出一些修改来适应双链表的需求。以下是修改后的代码:

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助手提供,问题来源于学员提问

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?