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
試過了! 仍然獲得第一個元素作爲輸出! – Vishal
提交輸入'3 4 5 6'(意思是3個項目 - 4,5,6)後,我得到預期的輸出和我的變化 - '4 5 6'。 – rgettman
是啊! 明白了! 犯了一個錯誤! – Vishal