All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0024_swap_nodes_in_pairs.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0001_0100.s0024_swap_nodes_in_pairs;

// #Medium #Top_100_Liked_Questions #Linked_List #Recursion #Data_Structure_II_Day_12_Linked_List
// #Udemy_Linked_List #Big_O_Time_O(n)_Space_O(1)
// #2023_08_09_Time_0_ms_(100.00%)_Space_40.7_MB_(10.83%)

import com_github_leetcode.ListNode;

/*
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
/**
 * 24 - Swap Nodes in Pairs\.
 *
 * Medium
 *
 * Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
 *
 * **Example 1:**
 *
 * ![](https://assets.leetcode.com/uploads/2020/10/03/swap_ex1.jpg)
 *
 * **Input:** head = [1,2,3,4]
 *
 * **Output:** [2,1,4,3] 
 *
 * **Example 2:**
 *
 * **Input:** head = []
 *
 * **Output:** [] 
 *
 * **Example 3:**
 *
 * **Input:** head = [1]
 *
 * **Output:** [1] 
 *
 * **Constraints:**
 *
 * *   The number of nodes in the list is in the range `[0, 100]`.
 * *   `0 <= Node.val <= 100`
**/
public class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null) {
            return null;
        }
        int len = getLength(head);
        return reverse(head, len);
    }

    private int getLength(ListNode curr) {
        int cnt = 0;
        while (curr != null) {
            cnt++;
            curr = curr.next;
        }
        return cnt;
    }

    // Recursive function to reverse in groups
    private ListNode reverse(ListNode head, int len) {
        // base case
        if (len < 2) {
            return head;
        }
        ListNode curr = head;
        ListNode prev = null;
        ListNode next;
        for (int i = 0; i < 2; i++) {
            // reverse linked list code
            next = curr.next;
            curr.next = prev;
            prev = curr;
            curr = next;
        }
        head.next = reverse(curr, len - 2);
        return prev;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy