java - 遍历节点列表,this = this.next在java中不起作用?

标签 java list linked-list this

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/

相关文章:

c# - 拆分逗号分隔的字符串并比较列表中的每个值

python - 如何解决引发 ValueError ("columns must have matching element counts") ValueError : columns must have matching element counts?

c - 它是 C 语言中的通用堆栈数据结构链表实现吗?

C++堆栈实现(作业)PT。二

c++ - 使用类递归创建链表,C++

java套接字权限问题

java - Spring HandlerMethodSelector.selectMethods 的替代品

java.security.AccessControlException : access denied (java.net.SocketPermission 127.0.0.1 :8081 connect, resolve) - 主要原因

python - CPython 源代码中的列表推导式在哪里实现?

java - 关于 ActionBarSherlock 将项目导入 Android Studio 的问题