解题思路
先找到当前要倒转的起点和终点,若终点为空,表明不够数量则将此时的p以后的链表直接插到tail后面,结束。若终点不为空,则采用头插法插到tail后面,并且tail移动到该链表的尾部,重复该过程。
代码
class Solution {
public:ListNode *reverseKGroup(ListNode *head, int k) {if (head == NULL || k == 0)return head;ListNode *first = new ListNode(0);ListNode *tail = first;ListNode *p = head;while (p){int t_k = k;ListNode *q = p;while (--t_k && q){q = q->next;}if (q == NULL){tail->next = p;break;}else{ListNode *end = q->next;while (p != end){ListNode *t = p->next;p->next = tail->next;tail->next = p;p = t;}while (tail->next)tail = tail->next;}}return first->next;}
};