24. Swap Nodes in Pairs

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

        ListNode cur = head;
        int count = 0;
        while (cur != null && count != 2){
            cur = cur.next;
            count++;
        }

        if (count == 2){
            cur = swapPairs(cur);

            while (count-- > 0){
                ListNode temp = head.next;
                head.next = cur;
                cur = head;
                head = temp;
            }
            head = cur;
        }

        return head;
    }
}

results for ""

    No results matching ""