java - Recursively reversing a linkedlist -


this question has answer here:

i'm trying reverse linkedlist using recursive calls, please let me know i'm going wrong, i'm not able catch reversed ll head. llnode linkedlist node , reversellrecursively.reverse function wrote reversing.

here code:

public class llnode {     private int data;     private llnode next;      public llnode(int data, llnode next) {         this.data = data;         this.next = next;     }      public int getdata() {         return data;     }      public void setdata(int data) {         this.data = data;     }      public llnode getnext() {         return next;     }      public void setnext(llnode next) {         this.next = next;     }      @override     public string tostring() {         return data + "->[" + (next!=null?next.data:"") + "]";     } }  public class reversellrecursively {      public static llnode newhead = new llnode(-1, null);      public static llnode reverse(llnode head, llnode newhead) {         if(head==null || head.getnext()==null) {             newhead = head;             return head;         }          llnode node = reverse(head.getnext(), newhead);         node.setnext(head);         head.setnext(null);         return node.getnext();     }      public static void main(string[] args) {         llnode ll = new llnode(1,new llnode(2, new llnode(3,  new llnode(3, new llnode(2,  new llnode(3, null))))));          reverse(ll , newhead);         system.out.println(newhead);      }  } 

you overcomplicating problem , work local variable has same name static member. should simpler:

public static llnode reverse(llnode previous) {     if(previous==null) {         return null;     }     llnode toreturn = (previous->getnext() == null) ? previous : reverse(previous.getnext());     previous.getnext().setnext(previous);     return toreturn; } 

note, toreturn new head.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -