Reverse single linked list Java
                                        
                    •
                    Java                                    
                How to reverse a singly linked list in blocks of some given size in O (n) time in place? 4
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;
    }
}
This is the node class:
public class Node{
   public int data;
   public Node next;
   public Node(int data,Node next){
      this.data = data;
      this.next = next;
   }
}
When I input 4 - > 3 - > 2 - > 1, I get the output 4 I debug it and set the pointer correctly, but I still don't understand why it only outputs 4
Solution
Node next = tmp.next;
Node next = tmp.next;
while(tmp != null){
So what happens when TMP = = null?
But you almost got it
Node before = null;
Node tmp = head;
while (tmp != null) {
    Node next = tmp.next;
    tmp.next = before;
    before = tmp;
    tmp = next;
}
head = before;
Or better (?) 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:      >  >  >
                
                            The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
                        
                                            
                        THE END
                    
                    
                    
                                                        二维码
                        
                        
                                                
                        