public class node {
int data ;
node next = null ;
public node(int newdata){
data = newdata ;
next = null ;
}
public void attach(int newdata){
node list = this ;
{
while(this.next != null){
System.out.println("---------------------------------------") ;
list = this.next ;
//this = this.next ; WHY CAN'T i DO THIS?
}
this.next = new node(newdata) ;
}
}
上面的代码有一个错误:它不会前进到下一个节点,因为 this = this.next 不起作用: “赋值的左侧必须是变量”。
我的解决方案是让变量节点“list”指向**这个**节点。然后照常遍历它:
public void attach2(int newdata){
node list = this ;
{
while(list.next != null){
System.out.println("---------------------------------------") ;
list = list.next ;
//this = this.next ; WHY CAN'T i DO THIS?
}
list.next = new node(newdata) ;// put new value as a node to end of list
}
}
有更好的方法吗?我可以避免使用“当前”而仅使用此关键字吗?
最佳答案
此
已保留 java keyword它指向当前实例,您不能将其用作变量,因此 this = this.next;
是语法错误。
关于java - 遍历节点列表,this = this.next在java中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25420227/