/
uizadcz
/
Algorithm
Обзор
Документация
Войти
/
uizadcz
/
Algorithm
Код
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
two_pointer/SwappingNodesinLinkedList.kt
44 строки
1 KB
ursa
TwoPointer
27 сен 2024, 14:26
27 сен 2024, 14:26
5e9624d
Код
Авторство
О чём код?
/** * You are given the head of a linked list, and an integer k. * * Return the head of the linked list after swapping the values of the * kth node from the beginning and the kth node from the end (the list is 1-indexed). * * Example: * var li = ListNode(5) * var v = li.`val` * Definition for singly-linked list. * class ListNode(var `val`: Int) { * var next: ListNode? = null * } */ class SwappingNodesinLinkedList { fun swapNodes(head: ListNode?, k: Int): ListNode? { if (head == null) return head var node = head var length = 0 while (node != null) { length += 1 node = node.next } var leftNode = head for (i in 1..(k - 1)) { leftNode = leftNode!!.next } var rightNode = head var rightLength = (length - k) for (i in 1..rightLength) { rightNode = rightNode!!.next } println(rightNode!!.`val`) println(leftNode!!.`val`) val buff = leftNode!!.`val` leftNode!!.`val` = rightNode!!.`val` rightNode!!.`val` = buff return head } }