在圆形双链接结构中链接节点

问题描述

我已经在这个圆形双链接结构上工作了一个星期,而我仍然坚持使用这种添加方法。我无法使节点正确链接,因为当我运行程序以打印出列表时,这并不是我所期望的。在下面,我附加了我的DNode(仅是普通节点类)代码以及ListCDLS(圆形双链接结构)代码,以及收到的意外输出。我在add方法中尝试了许多不同的算法,但都无济于事。唯一可以正常工作的是第一个if语句块。

public class DNode {
   
   private Object item;
   private DNode next;
   private DNode back;

   public DNode(Object item) {
       this.item = item;
       next = this;
       back = this;
   }
   
   public DNode(Object item,DNode nextNode,DNode backNode) {
       this.item = item;
       this.next = nextNode;
       this.back = backNode;
   }
\\omitted getters and setters for all data fields

public class ListCDLS implements ListInterface {
    
    private DNode tail;
    private int numItems;
    
    public ListCDLS() {
        tail = null;
    }
    
    @Override
    public boolean isEmpty() {
        if(this.size() == 0) {
            return true;
        }
        else {
            return false;
        }
    }

    @Override
    public int size() {
        return numItems;
    }
   
    public void add(int index,Object item) throws Listindexoutofboundsexception {
        if(isValidindex(index)) {
            if(this.isEmpty()) {
                DNode head = new DNode(item);
                tail = head;
            }
            //this is the one i am struggling with
            else if(index == 0 && !this.isEmpty()) {                
                DNode nextIndex = tail.getNext();
                DNode newHead = new DNode(item,nextIndex,tail);
                tail.setNext(newHead);
                tail.setBack(find(numItems-2));
                nextIndex.setBack(newHead);
                nextIndex.setNext(find(index+2));
            }
            else {
                
                //code I didn't start yet for the case of adding at index 1,2,3,4,5 etc.

            }
            numItems++;
        }
        else {
            throw new Listindexoutofboundsexception("The index is out of bounds!");
        }
    }

    private DNode find(int index) {
        DNode current;
        int possibleIndicies = numItems - 1;
        

        if( (possibleIndicies/2) < index ) {
            current = tail.getNext();
            
            for(int i = 0; i < index; i++)  {
                current = current.getNext();
            }
            
        }
        else {
            current = tail;
            
            for(int i = possibleIndicies; i > index; i--)  {
                current = current.getBack();
            }
            
        }   

        return current;
    }


所以,我要做的输入是:

项目:6,索引:0 项目:5,索引:0 项目:4,索引:0 项目:3,索引:0 项目:2,索引:0 项目:1,索引:0 项目:0,索引:0

因此,预期输出为: 0、1、2、3、4、5、6

尽管我收到: 6、0、1、2、4、5、6

任何帮助将不胜感激。我不知道该怎么做,因为我觉得我已经用尽了所有可能性,尽管我知道我的假设是错误的。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)