[LeetCode] 25. Reverse Nodes in k-Group

42 篇文章 0 订阅
37 篇文章 0 订阅

题目链接: 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;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值