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
'Programming > Kotlin' 카테고리의 다른 글
[백준/Kotlin] 동전 바꿔주기(2624) (0) | 2024.07.17 |
---|---|
[백준/Kotlin] 비즈 공예(1301) (1) | 2024.06.26 |
[백준/Kotlin] 이모티콘(14226) (0) | 2024.06.24 |
[LeetCode/Kotlin] 11. Container With Most Water (0) | 2024.06.24 |
[백준/Kotlin] 점수따먹기(1749) (0) | 2024.05.20 |