题目描述
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:
Given this linked list: 1->2->3->4->5
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.
解析
反转链表的进化版本,每K个分成一组进行反转,最后再连起来,递归可解,每次返回反转后的链表头,注意循环条件,如果找不到K个不反转,直接返回原来的序列,代码如下:
1 | public ListNode reverseKGroup(ListNode head, int k) { |
总结
十分常见的链表题,leetcode 25题老题目了,虽然是hard但是熟记规律也不难掌握,可以多写几遍,这样递归以及反转链表就能掌握得比较透彻了,如果面试问到这题而不会的话是很不应该的。