2016-01-20 24 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