题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*
* C语言声明定义全局变量请加上static,防止重复定义
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
struct ListNode* p = head, *h = head, *hr = head;
struct ListNode* q = head, *r;
int count = 0, t = k;
while(q){
q = q->next;
t--;
if(t == 0){
t = k;
count++;
}
}
printf("count=%d",count);
if(count == 0 || k == 1)return head;
q = p->next;
h = p;
hr = h;
int flag = 0,flag1 = 1;
while(count--){
p = h;
q = p->next;
t = k;
while(--t){
r = q->next;
q->next = p;
p = q;
q = r;
printf("t=%d ",t);
}
if(flag1){
head = p;
}
flag1 = 0;
if(flag){
hr->next = p;
hr = h;
}
flag = 1;
h->next = q;
h = q;
}
// h->next = NULL;
return head;
}