簡體   English   中英

為自定義LinkedList類添加方法

[英]Add method for custom LinkedList class

我一直在為自己正在研究的自定義鏈表實驗室研究這種添加方法。 插入新節點后,我無法弄清楚如何將值移動一個索引。 這是我的源代碼。

public void add(int index, Object element) throws IndexOutOfBoundsException {
    if(index > size() || index < 0) {
        throw new IndexOutOfBoundsException();
    }

    ListNode newNode = new ListNode(element, null);

    if(head == null) {
        head = newNode;
        return;
    }

    ListNode nextNode = head.nextNode;
    ListNode currNode = head;

    int i = 0;
    while(currNode!= null) {

        if(index == i) {
            break;
        }

        currNode = nextNode;
        //Breaks down here with null pointer exception
        nextNode = nextNode.nextNode;

    }

    currNode = newNode;
    currNode.nextNode = nextNode;
}

當您迭代最后一個節點時,它將拋出空指針,下一個節點指向空。 如果必須在最后一個節點中添加新節點,請檢查下一個節點是否為null。

同樣在您的代碼中,您並沒有增加i的價值,而是始終在遍歷整個列表。

我真的不知道您要在這里實現什么,我同意@Pritam Banerjee的評論。 但是代碼中的一個明顯問題是,您永遠不會增加i,因此您永遠也不會中斷while循環,並且在某些時候您將到達列表的末尾,nextNode.nextNode將為null,因此,您例外。 (還請注意,在currNode之前,nextNode.nextNode將為null。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM