题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
// 复杂问题分两步解决
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
#include <stdio.h>
struct ListNode* reverseRange(struct ListNode* head,int m,int n){
struct ListNode* p;
struct ListNode* pre;
int i;
p = head;
pre = NULL;
//到达指定的位置
for (i = 1;i<m;i++){
pre = p;
p = p->next;
}
struct ListNode* temp;
struct ListNode* temp_ne;
struct ListNode* q;
temp = p->next;
temp_ne = temp->next;
q = p;
for(i = 0;i<n-m;i++){
temp->next = p;
p = temp;
temp = temp_ne;
temp_ne = temp->next;
}
q->next = temp;
//特殊情况
if(pre == NULL){
return p;
}else{
pre->next = p;
return head;
}
}
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
struct ListNode* p_head;
struct ListNode* resul_l;
int count = 1;
int length = 1;
p_head = head;
resul_l = head;
while(p_head!=NULL){
p_head = p_head->next;
length++;
printf("%d",length);
}
while(count<length){
if(count % k == 0){
resul_l = reverseRange(resul_l,count-k+1,count);
}
count ++ ;
}
return resul_l;
}
查看16道真题和解析