簡體   English   中英

在單鏈列表中給定位置之后插入節點

[英]Inserting a Node after a given position in a singly linked list

我的代碼在Eclipse中工作正常,但在編程站點的編譯器中工作不正常。 此代碼是關於在給定位置添加節點。

Node InsertNth(Node head, int data, int position) {
    Node n = new Node();

    Node last = head;
    int count = 0;

    if (position == 0) {
        n.data = data;
        n.next = head;
        head=n;
        return n;
    }

    while (count < position) {
        count++;
        last = last.next;
    }
    n.data = data;
    n.next = last.next;
    last.next = n;
    return head;
}

您在循環中走得太遠,也不要檢查位置是否在范圍內:

Node InsertNth(Node head, int data, int position) {
    Node n = new Node();
    n.data = data;

    if (position == 0) {
        n.next = head;
        return n;
    }

    Node last = head;
    for (int count = 0; count < position-1; count++) {
        if (last == null) {
            return null;
        }
        last = last.next;
    }

    n.next = last.next;
    last.next = n;
    return head;
}

同樣,for循環更適合,並且其他一些事情可能會更好地重新安排。

暫無
暫無

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

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