Reverse Singly Linked List Java -


can tell me why code dosent work? want reverse single linked list in java: method (that doesnt work correctly)

public void reverselist(){     node before = null;     node tmp = head;     node next = tmp.next;     while(tmp != null){       if(next == null)          return;       tmp.next = before;       before = tmp;       tmp = next;       next = next.next;     } } 

and node class:

public class node{    public int data;    public node next;    public node(int data, node next){       this.data = data;       this.next = next;    } } 

on input 4->3->2->1 got output 4. debugged , sets pointers correctly still dont why outputs 4.

node next = tmp.next; while(tmp != null){ 

so happens when tmp == null?

you got it, though.

node before = null; node tmp = head; while (tmp != null) {     node next = tmp.next;     tmp.next = before;     before = tmp;     tmp = next; } head = before; 

or in nicer (?) naming:

node reversedpart = null; node current = head; while (current != null) {     node next = current.next;     current.next = reversedpart;     reversedpart = current;     current = next; } head = reversedpart; 

ascii art:

        <__<__<__ __ : reversedpart    : head                  (__)__ __ __ head :   current:      >  >  > 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -