Easy Java O(n) time and O(1) space solution


  • 0
    K
    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null || head.next == null)
              return head;
            ListNode first = head;
            ListNode second = head.next;
            ListNode third = second.next;
            ListNode temp = null;
            first.next = null;
            while(third != null){
                temp = second;
                second.next = first;
                first = temp;
                second = third;
                third = second.next;
            }
            second.next = first;
            return second;
        }
    }
    

  • 0
    M

    @karan33 You can make it work with 3 ListNode variables, instead of having 4 (first, second, third & temp)


Log in to reply
 

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