题目:
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个节点的逆转,逆转方式采用头结点插入方式
代码:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if(k<=1||head==NULL || head->next==NULL) return head;
int len=0;
ListNode* p=head;
while(p)//计算总长度
{
len++;
p=p->next;
}
if(k>len) return head;
/*完成k个节点的逆转*/
p=head;
ListNode *pre=p;
ListNode *last=NULL;
ListNode *mark=p;//记录逆转链表的第一个节点,以便将其与后续链表连接起来
p=p->next;
int n=1;
while(n!=k&&p!=NULL)
{
last=p->next;
p->next=pre;
mark->next=last;
pre=p;
p=last;
n++;
}
if(len-k>=k)
mark->next=reverseKGroup(p,k);//递归调用
else
mark->next=p;
head=pre;
return head;
}
};