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
ListNode *reverseKGroup(ListNode *head, int k) {
//此题主要是比较繁琐
ListNode *p = head;
int count = 0;
while (p)
{
++count;
p = p -> next;
}
int it = count / k;
ListNode *pre = NULL, *next = NULL, *preNext = NULL;
ListNode *headL = head, *q;
p = head;
//需要旋转it个子链表
for (int i = 0; i < it; ++i)
{
preNext = p;//用来链接后面子链表的节点
q = p -> next;//用来插入p节点之前的节点
int j = 1;
while (j < k)
{
next = q -> next;//记录子链表余下节点的头结点
//将q节点插入到p节点之前
q -> next = p;
p = q;
q = next;
++j;
}
//把以p为头结点的子链表链接到前一个子链表后
if (pre == NULL)
headL = p;
else
pre -> next = p;
pre = preNext;
p = q;
}
if (pre)
pre -> next = q;
return headL;
}