Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to reverse linkedlist in java ?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 440
    Comment on it

    There are two way to reverse a linked list that are using recursion or using iteration.

    This operation takes O(n) time complexity during iteration method.

    Here is the code to reverse linked list using iterator :

    public void reverseLinkedList(Node curNode){
    
     Node prevBode = null;
     Node nextNode = null;
    
     while(curNode != null){
    
     nextNode = curNode.next;
     curNode.next = prevNode;
     curNode = nextNode;
     prevNode = curNode;
     }
    return prevNode;
    }
    

    Here is method to reverse linked list recursively :

    public  Node reverseLinkList(Node node) {  
             if (node == null || node.next == null) {  
                 return node;  
             }  
    
         Node rest = reverseLinkList(node.next);  
         node.next.next = node;  
         node.next = null;  
        return rest;  
     }  
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: