k個(gè)一組翻轉(zhuǎn)鏈表
基本思路:
(1) 重點(diǎn):尋找確定k 個(gè)一組范圍恤磷,pre> [front, tail] > tailnext, 主要是tail,tail 必須非空
故while循環(huán)退出條件:cur->next != NULL
且主要不要使用 len--; 因?yàn)?cur->next && len-- , 每次對(duì)len--, len--放到循環(huán)體內(nèi)部塔嬉,保證最多執(zhí)行到0颤诀,也就是k 次窥摄;
int len = k;
while(cur->next && len) {
cur=cur->next;
len--;
}
if(len)
break;
(2) 對(duì)k 個(gè)做翻轉(zhuǎn)鏈表處理
(3)
struct ListNode* reverse(struct ListNode* head){
struct ListNode* result= NULL;
struct ListNode* cur=head;
while(cur) {
struct ListNode* next = cur->next;
cur->next=result;
result=cur;
cur=next;
}
//print(result);
return result;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k){
struct ListNode* dummy = (struct ListNode*) malloc(sizeof(struct ListNode));
dummy->next=head;
struct ListNode* pre=dummy;
while(1) {
struct ListNode* cur = pre;
int len = k;
while(cur->next && len) {
cur=cur->next;
len--;
}
if(len)
break;
struct ListNode* front = pre->next;
struct ListNode* tail = cur;
struct ListNode* tailnext= cur->next;
//break tail and tailnext
tail->next=NULL;
//
reverse(front);
pre->next = tail;
front->next=tailnext;
//
pre = front;
}
return dummy->next;
}