力扣 25. K 个一组翻转链表 链表+模拟

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
力扣 25. K 个一组翻转链表 链表+模拟_第1张图片

思路:没啥好办法,只能模拟了。 k k k个节点 k k k个节点的翻转即可,注意一下细节问题。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    //翻转链表 返回翻转后的链表的头节点
    ListNode* reverse(ListNode *head){
        if(!head||!head->next)
            return head;
        ListNode *cur=head,*nxt=head->next,*tmp;
        while(nxt){
            tmp=nxt->next;
            nxt->next=cur;
            cur=nxt;
            nxt=tmp;
        }
        return cur;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(!head||!head->next||k==1)
            return head;
        int cnt=0;
        ListNode ans(0);
        ListNode *cur=head,*tmp=head,*pre=&ans;
        while(1){
            tmp=cur;
            cnt=0;
            while(++cnt<k&&tmp)
                tmp=tmp->next;
            if(tmp){
                ListNode *nxt=tmp->next;
                tmp->next=nullptr;
                //翻转后cur为尾节点 tmp为头节点
                //需要通过上一段的尾节点pre 与该段连接起来
                tmp=reverse(cur);
                pre->next=tmp;
                pre=cur;
                cur=nxt;
            }
            else{
                pre->next=cur;
                break;
            }
        }
        return ans.next;
    }
};

你可能感兴趣的:(面试题,链表,模拟)