2017-06-24 72 views
-2

我正在嘗試這種方法,但我無法弄清楚這個問題。我認爲在insert()方法中存在一些問題,因爲我沒有使用遞歸,但是我無法準確指出它。 在此先感謝。如何使用java在鏈接列表中插入節點?

import java.io.*; 
import java.util.*; 

class Node { 
    int data; 
    Node next; 
    Node(int d) { 
     data = d; 
     next = null; 
    } 
} 

class Solution { 
public static Node insert(Node head,int data) { 
     //Some problem in this method 
     if(head==null) 
      return new Node(data); 
     else{ 
      Node nxt = head; 
      while(nxt!=null) 
       nxt = nxt.next; 
      nxt = new Node(data); 
      return head; 
     } 
    } 
    public static void display(Node head) { 
     Node start = head; 
     while(start != null) { 
      System.out.print(start.data + " "); 
      start = start.next; 
     } 
    } 

    public static void main(String args[]) { 
     Scanner sc = new Scanner(System.in); 
     Node head = null; 
     int N = sc.nextInt(); 

     while(N-- > 0) { 
      int ele = sc.nextInt(); 
      head = insert(head,ele); 
     } 
     display(head); 
     sc.close(); 
    } 
} 
+0

'nxt'鬆動,它沒有連接任何東西! – d9ngle

回答

0

你不想做

nxt = new Node(data); 

這實際上不會改變列表 - 它只會讓nxt指新節點的節點,而不是在的結束名單。實際上,你要插入一個新的節點時做

nxt.next = new Node(data); 
0

,以前節點的next必須設置爲這個新的節點 - nxt = new Node(data)設置變量。提示:結束循環時的節點的nextnull節點是null(重命名從nxtnodelast循環變量),並設置其next到新節點的代替。

換句話說,找到最後一個節點並將它的next設置爲新節點。

建議改進:不要返回列表頭,只要將其保存爲列表類的字段即可。最初它是空的並設置爲插入的第一個節點。這避免了你不必在列表之外維護它...