2016-01-20 69 views
0
package practice; 
import java.io.*; 
import java.util.*; 
class Node{ 
    int data; 
    Node next; 
    Node(int d){ 
     data=d; 
     next=null; 
    } 

} 
class practice 
{ 
    public static Node insert(Node head,int d) 
{ 
    if(head==null) 
     head = new Node(d); 
    else 
    { 
     Node cn = head; 
     while(cn!=null) 
      { 
      cn=cn.next; 
      cn = new Node(d); 
      cn= cn.next; 
     } 
    } 
    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); 
    } 
} 

我正在嘗試創建一個鏈表作爲指向列表的起始節點的節點。並將n元素添加到列表的尾部。但是當試圖顯示列表時,我只得到第一個元素作爲輸出。卡住鏈接列表 - 只顯示第一個節點時顯示

例如, 對於輸入

3 
4 
5 
6 

輸出是4當它應該是4 5 6

回答

4

insert方法未能插入,所述head已經存在的情況下的任何節點。它會創建一個新的Node,但會忽略它。

而是,搜索列表的末尾,查找nullnext參考。然後,將next引用設置爲新的Node

else 
{ 
    Node cn = head; 
    while (cn.next != null) 
    { 
     cn = cn.next; 
    } 
    cn.next = new Node(d); 
} 
+0

試過了! 仍然獲得第一個元素作爲輸出! – Vishal

+0

提交輸入'3 4 5 6'(意思是3個項目 - 4,5,6)後,我得到預期的輸出和我的變化 - '4 5 6'。 – rgettman

+0

是啊! 明白了! 犯了一個錯誤! – Vishal