/**
- struct ListNode {
- int val;
- struct ListNode *next;
- };
- C语言声明定义全局变量请加上static,防止重复定义 / /*
- 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- @param head ListNode类
- @param k int整型
- @return ListNode类 / static count = 0; struct ListNode swap(struct ListNode*head,int k) { if(count == 0||count<k) return head; struct ListNode *phead; phead = head; for(int i = 1;i <= k;i++) phead = phead->next; //部分交换 struct ListNode *p1,p2,p3; p1 = head; p2 = p1->next; p3 = p2->next; for(int i = 1;i<=k-2;i++) { p2->next = p1; p1 = p2; p2 = p3; p3 = p2->next; } p2->next = p1; count-=k; //部分节点的指向 head->next = swap(phead,k); return p2; } struct ListNode reverseKGroup(struct ListNode head, int k ) { // write code here if(head == NULL||k == 1) return head; struct ListNode *p = head; while(p != NULL) { p = p->next; count++; } if(count<k) return head; if(count == 1) return head; return swap(head,k); }