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

问题描述:

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

在哪个网站不起作用?你会得到什么错误?这是完整的例子吗? – TinyTheBrontosaurus

你走得太远与循环,也不会检查的位置是在范围:

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

+0

谢谢Yuval。你的代码有效。 – Karthik

+0

我猜for循环中的if条件是不需要的,因为它只有在last不为null时才进入for循环。 – Karthik

+0

@Karthik你怎么看?如果position大于列表的大小(加上一个),那么没有这个条件,你将在null('NullPointerException')上调用next。 –

如果它没有插入第0位和node -> new node -> next node顺序应安排你应该改变你的代码如下图所示,因为新节点将被插入(位置+ 1)个位置是这样的。

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