Given a linked list, reverse the nodes of a linked listk 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个我们才倒转,倒转的话其实就是一个子链表的倒序,然后将原来的子链表头链接到剩下的部分,并将倒序后的子链表头连接到上次的尾部。
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if (head == NULL || k < 2) return head;
ListNode * originalHead = head;
ListNode * lastTail = NULL;
while (1) {
int counter = 1;
ListNode * temp = originalHead;
while (temp && counter < k) { // 计算是否需要倒序
counter++;
temp = temp->next;
}
if (counter == k && temp) { // 如果要倒序
ListNode * subHead = originalHead; // 子链表头
ListNode * nextNode = (subHead ? subHead->next : NULL);
ListNode * nextNext = (nextNode ? nextNode->next : NULL);
int times = k - 1; // 计算需要倒序操作的次数
while (times--) { // 操作过程
nextNode->next = subHead;
subHead = nextNode;
nextNode = nextNext;
nextNext = (nextNode ? nextNode->next : NULL);
}
if (lastTail == NULL) { // 如果这次倒序是第一次
head = subHead;
lastTail = originalHead;
} else { // 否则
lastTail->next = subHead;
lastTail = originalHead;
}
originalHead->next = nextNode; // 更新下一次子链表头
originalHead = originalHead->next;
} else {
break;
}
}
return head;
}
};