k个一组反转链表

本文介绍了如何解决LeetCode题目中的一个链表问题,要求将链表中每k个节点作为一个组进行反转,确保在组内节点数不足k时也一并处理。代码展示了如何实现这个功能,包括创建链表、反转操作以及主函数示例。
摘要由CSDN通过智能技术生成

和leetcode上原题不同的是,如果最后一组元素构成的子链表长度小于k,则一并反转

代码如下:

#include <iostream>

using namespace std;

struct Node
{
    int value;
    Node* next = nullptr;
    Node(int v) :value(v) {}
};

Node *reverseList(Node *head, Node *tail)
{
    Node* tailAfterReverse = head->next;
    while (head->next != tail)
    {
        Node* temp = head->next;
        head->next = temp->next;
        temp->next = tail->next;
        tail->next = temp;
    }
    return tailAfterReverse;
}

void reverseListKGroup(Node* head, size_t k)
{
    if (head->next == nullptr)
        return;

    Node* tail = head->next;
    Node* first = head;
    while (true)
    {
        size_t count = 1;
        while (tail->next != nullptr && count < k)
        {
            tail = tail->next;
            ++count;
        }
        first = reverseList(first, tail);
        if (first->next == nullptr)
            break;
        tail = first->next;
    }
}

int main()
{
    const int N = 10;
    size_t k = 2;
    Node* head = new Node(-1);
    Node* tail = head;
    for (int i = 1; i <= N; ++i)
    {
        Node* cur = new Node(i);
        tail->next = cur;
        tail = cur;
    }

    cout << k << "个一组反转前:" << endl;
    tail = head->next;
    while (tail != nullptr)
    {
        cout << tail->value << " ";
        tail = tail->next;
    }
    cout << endl;

    reverseListKGroup(head, k);

    cout << k << "个一组反转后:" << endl;
    tail = head->next;
    while (tail != nullptr)
    {
        cout << tail->value << " ";
        tail = tail->next;
    }
    cout << endl;



    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值