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 个,保持不变。
不能改变节点值,只能改变节点顺序。
空间复杂度为 O(1)。
例如,链表为:1->2->3->4->5
当 k = 2,返回:2->1->4->3->5
当 k = 3,返回:3->2->1->4->5
分析:
只需每次找先找到 k 个节点,若满足则反转,否则保留不变。
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
/*首先查找反转长度,满足则反转此段*/
int count = 0;
struct ListNode *phasReverse = NULL, *ppartHead = NULL, *p = head;
struct ListNode *pre = NULL, *cur = NULL, *ne = NULL;
/*空或者只一个节点或者翻转0次或1次*/
if(!head || !head->next || 0 == k || 1 == k)
{
return head;
}
while(p)
{
if(NULL == phasReverse) /*链表头*/
{
p = head;
}
pre = p;/*记录待翻转部分的开始*/
count = 0;
while(p && count++ < k)/*查找是否满足k*/
{
p = p->next;
}
if(!p && count < k)/*不足k个节点*/
{
return head;
}
/*翻转该部分*/
ppartHead = pre;
ne = pre->next;
while(ne != p)
{
cur = ne;
ne = ne->next;
if(ppartHead == pre)
{
ppartHead = cur;
cur->next = pre;
}
else
{
cur->next = ppartHead;
ppartHead = cur;
}
}
/*将翻转后部分加入到前面已经翻转部分结尾*/
if(NULL == phasReverse)/*第一次翻转*/
{
phasReverse = ppartHead;
head = phasReverse;
}
else
{
phasReverse->next = ppartHead;
}
phasReverse = pre;
phasReverse->next = p;/*将未翻转的和已翻转部分连接在一起*/
}
return head;
}