当前位置: 代码迷 >> 综合 >> leetcode练习题 reverse-nodes-in-k-group
  详细解决方案

leetcode练习题 reverse-nodes-in-k-group

热度:10   发布时间:2023-12-15 09:58:28.0

解题思路

先找到当前要倒转的起点和终点,若终点为空,表明不够数量则将此时的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;}
};
  相关解决方案