Java simple recursive solution


  • 28
    F

    Starting to see that recursion is the perfect tool for (many) linked list problems (this one + merging list problem).

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head == null || head.next == null) return head;
            ListNode second = head.next;
            ListNode third = second.next;
            
            second.next = head;
            head.next = swapPairs(third);
            
            return second;
        }
    }

  • 0
    M

    Very simple and straightforward solution in recursive way. Can you explain Big O on time and space for this solution? MANY THX!


  • 0

    very clean and effective solution. But you will incur extra memory O(n) due to recursive stack.


Log in to reply
 

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