K 个一组翻转链表(力扣)

https://leetcode.cn/problems/reverse-nodes-in-k-group/?envType=study-plan-v2&envId=top-interview-150
思路:
先求长,然后分段反转
反转的题:https://blog.csdn.net/2301_81278039/article/details/135888952?spm=1001.2014.3001.5501
代码:

/**
 * 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) {
        ListNode* dummynode = new ListNode(-1);
        dummynode->next = head;
        ListNode* cur = head;
        int length = 0;
        while(cur)
        {
            cur = cur->next;
            length ++;
        }
        ListNode* pre = dummynode,*next;
        for(int i = 0;i < length / k;i ++)
        {
            if(i != 0)
            {
                for(int j = 0;j < k;j ++)
                {
                    pre = pre->next;
                }
            }
            cur = pre->next;
            for(int j = 0;j < k - 1;j ++)
            {
                next = cur->next;
                cur->next = next->next;
                next->next = pre->next;
                pre->next = next;
            }
        }
        return dummynode->next;
    }
};

你可能感兴趣的:(C++从零开始,链表,leetcode,数据结构)