Programming/Kotlin

[LeetCode/Kotlin] 24. Swap Nodes in Pairs

코딩뽀시래기 2024. 6. 26. 11:07
728x90

문제

https://leetcode.com/problems/swap-nodes-in-pairs

 

풀이

  • 재귀로 풀이
  • next와 next.next를 고려해서 swap해야한다
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun swapPairs(head: ListNode?): ListNode? {
        if (head == null || head.next == null) return head;
        var second = head.next;
        var third = second.next;

        second.next = head;
        head.next = swapPairs(third);

        return second;
    }
}
728x90