Reverse Nodes in k-Group

本文介绍了一种算法,该算法将链表中的节点每K个为一组进行翻转,并详细阐述了实现过程,包括如何计算需要翻转的次数、如何编写翻转链表前N个节点的函数等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a linked list, reverse the nodes of a linked list k at a time and return its modified 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


pro:将一个链表每k个节点为一组翻转,最后不足k个数的不用翻转

sol:先求链表的长度,计算出需要翻转的次数,写一个专门的翻转链表前n个节点的函数,每一组结束后返回头,记录尾,for循环里链接一下。

code:

class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head==NULL||head->next==NULL||k<=1)
            return head;
        int length=0;
        ListNode *cur=head;
        while(cur!=NULL)
        {
            length++;
            cur=cur->next;
        }
        if(k>length) k=1;
        int countt = length/k;
        int i;
        ListNode *res;
        ListNode *last,*nextRound;
        for(i=0;i<countt;i++)
        {
            if(i==0)
            {
                res = reverse(head,k,last,nextRound);
            }else
            {
                last->next = reverse(nextRound,k,last,nextRound);
            }
        }
        if(length%k==0) last->next=NULL;
        else last->next = nextRound;
        return res;
    }
    //指针传递,函数内部是copy一份,但指针拷贝和指针指向的地址相同,因此值会改变。但如果想改变指向的东西,即地址改变,要传指针引用
    //NULL是0,啥也不是,不能做为左值。不能做为指针引用的实参
    ListNode* reverse(ListNode *head,int k,ListNode*& last,ListNode*& nextRound)//这里需要注意用指针的引用才能改变指针指向内容
    {
        ListNode *cur,*next;
        int i;
        cur=head;
        next = cur->next;
        for(i=0;i<k;i++)
        {
            if(i==k-1)
                nextRound = cur->next;
            cur->next = last;
            last = cur;
            if(i!=k-1)
            {
                cur = next;
                next = cur->next;
            }
        }
        last = head;
        
        return cur;
    }
    
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值