# LeetCode 25. K 个一组翻转链表(递归,Kotlin)

## 25. K 个一组翻转链表

k 是一个正整数，它的值小于或等于链表的长度。

#### 25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

Note:

Only constant extra memory is allowed.

You may not alter the values in the list’s nodes, only nodes itself may be changed.

1.分组反转链表操作

2.边界处理

### 代码

class Solution {
fun reverseKGroup(head: ListNode?, k: Int): ListNode? {
}

// 找到tail的地址
for (i in 0..(k - 1)) {
// 当这一组链表节点数小于k,直接返回
if (tail == null) {
}
// 指针逐一后移,一直移到k-1位置=tail
tail = tail.next
}

// 反转该组

}

fun reverse(head: ListNode?, tail: ListNode?): ListNode? {
// cur pre
var pre: ListNode? = null
// cur next
var next: ListNode?

// cur->cur.next
while (cur != tail) {
// next持有cur的next节点
next = cur?.next
// 反转cur节点的next为pre
cur?.next = pre
// 指针向后移到下一个节点
pre = cur
cur = next
}
return pre
}

}

class ListNode(var value: Int) {
var next: ListNode? = null
override fun toString(): String {
return "ListNode(value=$value, next=$next)"
}
}



fun main() {
run {
val listNode1 = ListNode(1)
val listNode2 = ListNode(2)
val listNode3 = ListNode(3)
val listNode4 = ListNode(4)
val listNode5 = ListNode(5)
listNode1.next = listNode2
listNode2.next = listNode3
listNode3.next = listNode4
listNode4.next = listNode5
listNode5.next = null
val ans = reverseKGroup(listNode1, 2)
println(ans)
}

run {
val listNode1 = ListNode(1)
val listNode2 = ListNode(2)
val listNode3 = ListNode(3)
val listNode4 = ListNode(4)
val listNode5 = ListNode(5)
listNode1.next = listNode2
listNode2.next = listNode3
listNode3.next = listNode4
listNode4.next = listNode5
listNode5.next = null
val ans = reverseKGroup(listNode1, 3)
println(ans)
}

}


ListNode(value=2, next=ListNode(value=1, next=ListNode(value=4, next=ListNode(value=3, next=ListNode(value=5, next=null)))))

ListNode(value=3, next=ListNode(value=2, next=ListNode(value=1, next=ListNode(value=4, next=ListNode(value=5, next=null)))))

## 反转链表

Example:

Input: 1->2->3->4->5->NULL

Output: 5->4->3->2->1->NULL

A linked list can be reversed either iteratively or recursively. Could you implement both?

/**
* Example:
* var li = ListNode(5)
* var v = li.val
* class ListNode(var val: Int) {
*     var next: ListNode? = null
* }
*/
class Solution {
var pre:ListNode? = null
var next:ListNode? = null

while(cur!=null){
next = cur.next
cur.next = pre
pre = cur
cur = next
}

return pre

}
}


## 参考资料

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

https://leetcode-cn.com/submissions/detail/67275479/

## Kotlin开发者社区

High availability, high performance, high real-time large-scale distributed system architecture design