用Java制作链表
我通过使用for循环逐个扫描链接列表中的元素来添加元素,但在打印列表时,最后出现了0。最后一个节点指向null,但列表中仍有一个元素为0。我在下面提供我的源代码,然后输入用Java制作链表,java,exception,data-structures,Java,Exception,Data Structures,我通过使用for循环逐个扫描链接列表中的元素来添加元素,但在打印列表时,最后出现了0。最后一个节点指向null,但列表中仍有一个元素为0。我在下面提供我的源代码,然后输入 import java.util.Scanner; import static java.lang.System.out; class Node{ int data; Node next; Node(){ this.next=null; } Node(int
import java.util.Scanner;
import static java.lang.System.out;
class Node{
int data;
Node next;
Node(){
this.next=null;
}
Node(int data){
this.data=data;
this.next=null;
}
}
public class MyClass{
public static void main(String args[]) {
Node head=new Node();
Node temp=head;
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
for(int i=1;i<=size;i++){
temp.data=sc.nextInt();
temp.next=new Node();
temp=temp.next;
}
temp=null;
while(head!=null){
out.print(head.data+" ");
head=head.next;
}
}
}
import java.util.Scanner;
导入静态java.lang.System.out;
类节点{
int数据;
节点下一步;
节点(){
this.next=null;
}
节点(int数据){
这个。数据=数据;
this.next=null;
}
}
公共类MyClass{
公共静态void main(字符串参数[]){
节点头=新节点();
节点温度=头;
扫描仪sc=新的扫描仪(System.in);
int size=sc.nextInt();
对于(int i=1;i,链表最后一个节点中的next
指针应为空,以表示它是最后一个节点
在您的情况下,您将保持它为“NOTNULL”。在for
循环中,只要不实例化next
指针(如果它是您正在读取的最后一个元素)
for(int i=1;i<=size;i++){
temp.data=sc.nextInt();
if(i != size) {
temp.next=new Node();
temp=temp.next;
}
}
for(int i=1;i您正在循环外部创建头节点,并在其中创建一个新节点。
因此,您将获得1个额外节点
您可以尝试以下方法:
public static void main(String args[]) {
Node head=null;
Node last=null;
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
for(int i=1;i<=size;i++){
if (head == null){
head = new Node();
last = head;
} else {
last.next = new Node();
last = last.next();
}
last.data=sc.nextInt();
}
while(head!=null){
out.print(head.data+" ");
head=head.next;
}
}
publicstaticvoidmain(字符串参数[]){
节点头=空;
节点last=null;
扫描仪sc=新的扫描仪(System.in);
int size=sc.nextInt();
对于(int i=1;i而言,问题在于,即使在退出循环后将temp=null设置为空,仍然有一个额外的未分配节点
最简单的修复方法是删除for循环中的“=”符号,以便在最后一个节点之后退出循环,然后分配最终值,如下所示:
for(int i=1;i<size;i++){
temp.data=sc.nextInt();
temp.next=new Node();
temp=temp.next;
}
temp.data=sc.nextInt();
for(int i=1;i而您的问题是什么?由于Node head=new Node();
在循环之前和temp.next=new Node(),您的代码创建size+1
节点
在循环内部;但是只有大小
从用户输入中接收值。因此其中一个节点的数据
的默认值仍然为0。实际上,我在问如何在打印元素时停止0,因为我无法停止创建新节点。我需要一个直接的措施来停止此crea在不添加额外代码的情况下执行此操作。