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
思路:将子链表逆置后插入最终链表;
注意
旧链表位置
新链表头尾指针声明 & 插入顺序
class Solution {
public:
void reverse(ListNode * group_head,ListNode *group_tail)
{
ListNode * head = new ListNode(-1);
ListNode * p = group_head;
head->next = p;
ListNode * q = p->next;
p = q;
while(p!=group_tail)
{
q = q->next;
p->next = head->next;
head->next = p;
p = q;
}
p->next = head->next;
head->next = p;
}
ListNode* reverseKGroup(ListNode* head, int k) {
if(head == NULL || head->next == NULL || k == 1)
return head;
ListNode * p_l = head;
int num = 0;
while(p_l!=NULL)
{
num++;
p_l = p_l ->next;
}
if(num <k)
return head;
ListNode * new_head = new ListNode(-1);//新链表头节点
ListNode * tail = NULL;//新链表尾节点
ListNode * temp_first;//翻转的头节点
ListNode * temp_end;//翻转的尾节点
ListNode * p = head;//旧链表的工作指针
temp_first = p;
int count = 1;
temp_end = p;
while(p!=NULL)
{
p = p->next;
if(count == k)
{
reverse(temp_first,temp_end);
if(new_head->next == NULL)
{
new_head->next = temp_end;
tail = temp_first;
}
else
{
tail->next = temp_end;
tail = temp_first;
}
count = 1;
temp_first = temp_end = p;
continue;
}
if(p == NULL)
break;
count++;
temp_end = p;
}
if(count < k)
{
tail->next = temp_first;
}
return new_head->next;
}
};