/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/* 检查是否可反转 */
int ChechList(struct ListNode *head, int k)
{
int count = 1;
struct ListNode *temp = head;
while (temp) {
if (count == k) {
return 1;
}
temp = temp->next;
count++;
}
return 0;
}
struct ListNode *Reverse(struct ListNode *head, int k)
{
struct ListNode *preTrt = head;
struct ListNode *trt = head;
struct ListNode *pre = head;
struct ListNode *cur = head;
struct ListNode *next = head;
struct ListNode *pHead = head; /* 反转后新的头节点 */
while (ChechList(cur, k) == 1) {
preTrt = trt; /* 记录反转区间的前一个节点,反转后用于连接反转区间 */
pre = cur;
cur = cur->next;
trt = pre; /* 记录反转区间的开始节点,反转后为反转区间的最后一个节点,用于连接后面节点 */
for (int i = 1; i < k; i++) {
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
trt->next = cur; /* 连接后反转区间的后面节点 */
if (preTrt == trt) {
pHead = pre; /* 新的头节点 */
} else {
preTrt->next = pre; /* 反转前一个节点连接反转区间反转后的区间 */
}
}
return pHead;
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k ) {
// write code here
return Reverse(head, k);
}