Simple JAVA solution using recursion


  • 0
    M

    Just switched the value between adjacent node

    public class Solution {
        public ListNode swapPairs(ListNode head) {
            if (head==null || head.next==null) {
                return head;
            }
            int tmp = head.val;
            head.val = head.next.val;
            head.next.val = tmp;
            swapPairs(head.next.next);
            return head;
        }
    }
    

Log in to reply
 

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