在单个链接列表中的给定位置之后插入节点

时间:2017-07-30 20:06:50

标签: java

我的代码在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;
}

1 个答案:

答案 0 :(得分:0)

你对循环走得太远,也不检查位置是否在范围内:

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循环更合适,其他一些东西可以更好地重新排列。