Leetcode 25. K 个一组翻转链表(朴实无华的模拟法)

2021年3月4日 周四天气晴 【不悲叹过去,不荒废现在,不惧怕未来】



1. 题目简介

25. K 个一组翻转链表
在这里插入图片描述

2. 题解(模拟法)

朴实无华的模拟法:思路类似于 Leetcode 92. 反转链表 II,只不过更复杂一些,需要每次根据头尾结点反转k个结点,然后把断掉的地方接上,直到剩下的结点不足k个为止。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
    
    
        if(k==1) return head;
        ListNode* hair = new ListNode(0);
        hair->next = head;
        ListNode* pre = hair;

        while(head){
    
    
            ListNode* cur = pre;
            // 查看剩余部分长度是否大于等于 k
            for(int i=0;i<k;++i){
    
    
                cur = cur->next;
                if(cur==nullptr)
                    return hair->next;         
            }
            ListNode* tail = cur;
            pair<ListNode*,ListNode*> p = reverseBetween(head,tail);
            head = p.first;
            tail = p.second;

            // 把子链表重新接回原链表
            pre->next = head;
            pre = tail;
            head = tail->next;
        }
        return hair->next;
    }

    // 翻转一个子链表,并且返回新的头与尾
    pair<ListNode*,ListNode*> reverseBetween(ListNode* head, ListNode* tail){
    
    
        ListNode* nex = head->next;
        ListNode* cur = head;
        while(cur!=tail){
    
    
            head->next = nex->next;
            nex->next = cur;
            cur = nex;
            nex = head->next;
        }
        return {
    
    tail,head};
    }
};

参考文献

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/k-ge-yi-zu-fan-zhuan-lian-biao-by-leetcode-solutio/

猜你喜欢

转载自blog.csdn.net/m0_37433111/article/details/114361609
今日推荐