[LeetCode] 25. Reverse Nodes in k-Group

题目链接: https://leetcode.com/problems/reverse-nodes-in-k-group/description/

Description

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

解题思路

题意大致为,将链表每 k 个结点分为一组,每组进行反转,并且剩下的不足 k 个结点的组不处理。

组数可以通过先计算链表长度 len,然后用 len / k 获得。

当前组的头 cur_h 从链表头开始,先计算下一组的头的指针 next_h,然后在 cur_hnext_h 范围内反转结点。

这个步骤跟整个链表反转是一样的,只是终止条件的判断不是 NULL,而是 next_h,另外这个步骤要使得 cur_h->next = next_h,这样确保了最后不足 k 个结点的组也被连上。

最后,将上一组的尾结点 last_hnext 指针指向当前组反转后的头结点指针,并且更新 last_hcur_h 指针。

空间复杂度为 O(1)

Code

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        int len = 0;
        // 上一组未反转前的头
        ListNode* last_h = NULL;
        // 当前组未反转前的头
        ListNode* cur_h = head;
        // 下一组未反转前的头
        ListNode* next_h;
        ListNode *p, *q, *r;

        // 计算链表长度
        while (cur_h != NULL) {
            len++;
            cur_h = cur_h->next;
        }

        // n 为组数
        int n = len / k;
        cur_h = head;
        for (int i = 0; i < n; ++i) {
            // 计算下一组未反转前的头结点指针
            next_h = cur_h;
            for (int j = 0; j < k; ++j) {
                next_h = next_h->next;
            }

            // 开始反转
            q = next_h;
            p = cur_h;
            while (p != next_h) {
                r = p->next;
                p->next = q;
                q = p;
                p = r;
            }

            // 将上一组的尾结点连到当前组反转后的头
            if (last_h != NULL) {
                last_h->next = q;
            } else {
                head = q;
            }

            last_h = cur_h;
            cur_h = next_h;
        }

        return head;
    }
};

你可能感兴趣的:(C++,日常小题,LeetCode)