Java solutions. iteration and recursion


  • 0
    N

    reverse it iteratively:

    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head != null){
                ListNode next = head.next;
                head.next = null;
                while(next != null){
                    ListNode temp = next.next;
                    
                    next.next = head;
                    head = next;
                    next = temp;
                }
            }
            return head;
        }
    }
    

    reverse it recursively:

    public class Solution {
        public ListNode reverseList(ListNode head) {
            if(head == null) return head;
            ListNode next = head.next;
            head.next = null;
            
            return helper(head, next);
        }
        private ListNode helper(ListNode head, ListNode next){
            if(next == null) return head;
            ListNode temp = next.next;
            next.next = head;
            
            return helper(next, temp);
        }
    }

  • 0
    S

    sorry, i would want to ask, if the input is [1,2,3] then using your recursive code, 2.next is still 3 and 3.next is 2. is it ok?


Log in to reply
 

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