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
/**
* Definition for singly-linked list.* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
ListNode *p_pre=head,*p=head,*p_next=NULL;
int i=0,len=0,n=k;
if(head==NULL||head->next==NULL||k<=1)
return head;
while(p_pre)
{
len++;
p_pre=p_pre->next;
}
if(len<k)
return head;
p_pre=NULL;
while(n>0)
{
p_next=p->next;
p->next=p_pre;
p_pre=p;
p=p_next;
n--;
}
if(len-k>=k)
head->next=reverseKGroup(p,k);//递归调用
else
head->next=p;
return p_pre;//注意返回值就是第一个group反转后最后一个值的指针
}
};
本文介绍了一种算法,该算法可以将链表每K个节点为一组进行翻转,并返回修改后的链表。文章详细阐述了实现过程,包括递归调用以处理剩余节点。同时强调了不允许改变节点值,只能更改节点本身这一约束。
446

被折叠的 条评论
为什么被折叠?



