且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中使用DoublyLinkedList编写添加/插入方法

更新时间:2023-12-04 07:53:58

这一点都不容易,但是我找到了问题的答案。

This was not easy at all, however I figured out the answer to my question.

 @SuppressWarnings("unchecked")
 public void add(int index, E value)
 {
    if(index > size || index < 0)
    {
        throw new IndexOutOfBoundsException();
    }
    if (first == null)
    {
        Node n = new Node(value, null, null);
        n.next = n;
        n.prev = n;
        first = n;
    }
    else
        {
        Node current = first;
        for (int i = 0; i < index; i++)
        {
            current = current.next;
        }
        //current points to node that will follow new node.
        Node n2 = new Node(value, current, current.prev);
        current.prev.next = n2;
        current.prev = n2;
        //update first if necessary.
        if(index == 0)
        {
            first = n2;
        }
    }
    size++;
}