题解 | #链表中的节点每k个一组翻转#

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

/**
 * struct ListNode {
 *  int val;
 *  struct ListNode *next;
 *  ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
#include <fstream>
class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        ListNode* rethead = nullptr;
        ListNode* start = head, *end = head;
        ListNode* pre = nullptr;
        while (end != nullptr) 
        {
            //end向后偏移k-1步,与start形成k个节点的区间
            for (int i = 1; i < k && end ; ++i) {
                end = end->next;
            }
            //不足k个
            if(end == nullptr ) {
                if(rethead == nullptr) rethead = head;
                else pre->next = start;
                break;
            }
            ListNode* nex= end->next;
            ListNode* cur = start->next, *left = start, *right = nullptr;
            left->next = nullptr;
            //区间反转
            while (left != end) {
                right = cur->next;
                cur->next = left;
                left = cur;
                cur = right;
            }
			//拼接
            if (rethead == nullptr) {
                rethead = end;
            } else {
                pre->next = end;
            }
			//重定位start end nex
            pre = start;
            start =  nex;
            end = nex;
        }
        return rethead;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务