题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
int getListSize(struct ListNode *head)
{
int cnt=0;
while(head)
{
head=head->next;
cnt++;
}
return cnt;
}
struct ListNode* reverseK(struct ListNode *head, int start,int end)
{
struct ListNode *p,*q,*tmp,*subhead,*subend,*subheadpre,*subendnext,*temp;
int offset = start;
int len = end - start;
tmp = head;
p = tmp;
subheadpre=NULL;
while(offset)
{
subheadpre = tmp;
tmp = tmp->next;
p = tmp;
offset--;
}
subhead = p;
while(len)
{
p=p->next;
len--;
}
subend = p;
subendnext=p->next;
if(subheadpre)
{
subheadpre->next=NULL;
}
subend->next = NULL;
subend = subhead;
temp = subhead->next;
q = temp;
subhead->next = NULL;
while(temp)
{
temp = q->next;
q->next= subhead;
subhead = q;
q = temp;
}
if(subheadpre)
{
subheadpre->next = subhead;
}
else {
{
head = subhead;
}
}
subend->next = subendnext;
return head;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
int len=0;
int groupcnt=0;
int i=0;
if(k==0)
{
return head;
}
len = getListSize(head);
groupcnt = len/k;
if(groupcnt==0)
{
return head;
}
for(i=0;i<groupcnt;i++)
{
head = reverseK(head,i*k,(i+1)*k - 1);
}
return head;
}
查看6道真题和解析