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
pro:将一个链表每k个节点为一组翻转,最后不足k个数的不用翻转
sol:先求链表的长度,计算出需要翻转的次数,写一个专门的翻转链表前n个节点的函数,每一组结束后返回头,记录尾,for循环里链接一下。
code:
class Solution {
public:
ListNode *reverseKGroup(ListNode *head, int k) {
if(head==NULL||head->next==NULL||k<=1)
return head;
int length=0;
ListNode *cur=head;
while(cur!=NULL)
{
length++;
cur=cur->next;
}
if(k>length) k=1;
int countt = length/k;
int i;
ListNode *res;
ListNode *last,*nextRound;
for(i=0;i<countt;i++)
{
if(i==0)
{
res = reverse(head,k,last,nextRound);
}else
{
last->next = reverse(nextRound,k,last,nextRound);
}
}
if(length%k==0) last->next=NULL;
else last->next = nextRound;
return res;
}
//指针传递,函数内部是copy一份,但指针拷贝和指针指向的地址相同,因此值会改变。但如果想改变指向的东西,即地址改变,要传指针引用
//NULL是0,啥也不是,不能做为左值。不能做为指针引用的实参
ListNode* reverse(ListNode *head,int k,ListNode*& last,ListNode*& nextRound)//这里需要注意用指针的引用才能改变指针指向内容
{
ListNode *cur,*next;
int i;
cur=head;
next = cur->next;
for(i=0;i<k;i++)
{
if(i==k-1)
nextRound = cur->next;
cur->next = last;
last = cur;
if(i!=k-1)
{
cur = next;
next = cur->next;
}
}
last = head;
return cur;
}
};