24. Swap Nodes in Pairs

  • Source : Link
  • Author : Han
  • Date : 2022-02-17

Problems

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

1
2
3
Input: head = [1,2,3,4]
Output: [2,1,4,3]

Example 2:

1
2
3
Input: head = []
Output: []

Example 3:

1
2
3
Input: head = [1]
Output: [1]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/**
 * 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? {
        return when {
            head?.`val` == null -> null
            head.next == null -> head
            else -> {
                val remainNode = swapPairs(head.next!!.next)
                val tempNode = head.next
                tempNode?.next = head
                tempNode?.next!!.next = remainNode
                tempNode
            }
        }
    }
}