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
24题的扩展。还是递归解决,每次逆置k个节点,若链表当前剩余长度小于k,则直接返回
ListNode* reverseKGroup(ListNode* head, int k) {
int len=0;
ListNode* p=head;
while(p){len++;p=p->next;}
if(k==1 || k>len)return head;
ListNode* p1=head;
ListNode* p2=p1->next;
ListNode* p3=NULL;
if(p2)p3=p2->next;
for(int i=1;i<=k-1;i++){
p2->next=p1;
if(i==k-1)break;
p1=p2;
p2=p3;
if(p3)p3=p3->next;
}
head->next=reverseKGroup(p3,k);
return p2;
}
本文介绍了一种算法,该算法可以将链表每K个节点为一组进行翻转,并保持剩余节点不变。通过递归的方式实现,不改变节点值,仅调整节点连接顺序,且只使用常数内存。

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



