Given a linked list, swap every two adjacent nodes and return its head.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
/**
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class Solution {
fun swapPairs(head: ListNode?): ListNode? {
val h = ListNode(0)
h.next = head
var left: ListNode = h
var right: ListNode? = left.next?.next
while (right != null) {
swapPair(left, right)
left = left.next!!.next!!
right = left.next?.next
}
return h.next
}
private fun swapPair(left: ListNode, right: ListNode) {
left.next?.next = right.next
right.next = left.next
left.next = right
}
}
/**
* Definition for singly-linked list.
* class ListNode(var `val`: Int = 0) {
* var next: ListNode? = null
* }
*/
class Solution {
fun swapPairs(head: ListNode?): ListNode? {
val n = head?.next ?: return head
head.next = swapPairs(n.next)
n.next = head
return n
}
}