Reverse Nodes in k-Group : https://leetcode.com/problems/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.
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 个节点的链表。然后对每一组链表,运行一次单链表逆序。
单链表逆序:http://blog.csdn.net/quzhongxin/article/details/45576529
关键点是: 怎样把各个组逆序后的链表,又一次组合起来。
我们首先通过递归方式,找出 1 个 K Group的头和尾(注:不包含这个尾节点),然后以这一个K Group的尾作为下一个K Group的头。 当对当中一个 K Group运行单链表逆序时,应该注意:最后新链表尾节点指向的是下一个K Group的开头。而推断是否为新链表尾部。则推断 prev == NULL ,由于我们设定一个链表的尾部为NULL.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (head == NULL || head->next == NULL || k < 2)
return head;
ListNode* k_group = head; // 一个K组以head開始以k_group结束(不包含k_group)
for (int i = 0; i < k ; i++) {
if (k_group)
k_group = k_group->next;
else
return head;
}
// next_k_group:下一个 K Group 的 head
ListNode* next_k_group = reverseKGroup(k_group, k);
ListNode* prev = NULL;
ListNode* cur = head;
while (cur != k_group) {
ListNode* next = cur->next;
cur->next = (prev == NULL) ? next_k_group : prev; // 逐个逆序,prev == NULL 代表是逆序完毕后的尾节点
prev = cur;
cur = next;
}
return prev;
}
};