Simple Java Solution with O(n) and without extra space


  • 0
    K

    Simple Java Solution with O(n) and without extra space
    ....
    public class Solution {
    public ListNode reverseList(ListNode head) {

         ListNode pre = null; //pointer for previous node
         ListNode curr = head; // pointer for current node
         
        while(head!=null) //iterates entire list so O(n)
        {
            ListNode t = head.next; //Stores next pointer
            curr = head; // 2nd pointer for current node for changing their next Node
            curr.next = pre;
            pre = head;// previous pointer updated
            
            
            head = t;//assigns saved pointer from line 17 
        }
       return curr; 
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.