题目描述:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For 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
解题思路:
仍然是采用递归的方法,跟上一题类似。按照k个数字为一段的方法递归判断。如果该段长度不够k,那么直接返回该段的值。否则将该段k个数字从第一个数字开始两个两个反转。
代码如下:
public ListNode reverseKGroup(ListNode head, int k) {
if (head == null)
return null;
ListNode tmp = head;
for (int i = 1; i < k; i++) {
tmp = tmp.next;
if (tmp == null)
return head;
}
ListNode nextRoundHead = tmp.next;
ListNode firstNode = head;
ListNode secondNode = head.next;
ListNode thirdNode;
for (int i = 1; i < k; i++) {
thirdNode = secondNode.next;
secondNode.next = firstNode;
firstNode = secondNode;
secondNode = thirdNode;
}
head.next = reverseKGroup(nextRoundHead, k);
return tmp;
}