Description
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.
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
Solution
以k为group去swap链表,比24. Swap Nodes in Pairs更具有普适性,hard级别,禁止修改node的val
每次截取k个节点,并记录下一个group的pHead节点,翻转此次k个节点并将首尾依次拼接到pPrev和pHead,继续循环,直至取不出k group
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (k == 1) {
return head;
}
ListNode *dummy = new ListNode(-1), *pPrev = dummy;
dummy->next = head;
while (1) {
int countK = k;
ListNode *pNode = pPrev, *pHead = pPrev->next;
while(countK-- && pNode) {
pNode = pNode->next;
}
if (pNode == NULL) {
return dummy->next;
}
ListNode *pNextHead = pNode->next;
pNode->next = NULL;
pPrev->next = this->reverseLinkList(pHead);
pHead->next = pNextHead;
pPrev = pHead;
}
return dummy->next;
}
ListNode* reverseLinkList(ListNode* head) {
ListNode* pNode = NULL;
while (head) {
ListNode* pNext = head->next;
head->next = pNode;
pNode = head;
head = pNext;
}
return pNode;
}
};
网友评论