leetcode 25. k个一组翻转链表

本文介绍了一种链表操作的算法,即每k个节点为一组进行翻转,同时保持了额外空间复杂度为常数。通过使用栈来辅助翻转过程,详细解释了如何在不改变节点值的情况下实现节点的交换。

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

题目:k个一组翻转链表

题目描述:

给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么将最后剩余节点保持原有顺序。

示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5

说明 :

你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

网址:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/

解题思路:

  1. 使用栈存储k个数据,每存储 st.size() == k ,则进行一次反转;
  2. 每次循环要记录返回的链表的最后一个节点 nextline , 为了链接下一个反转的首节点;
  3. 当st.size() < k 时,则将nextline->next = st 中的最下面的元素;
class Solution {
public:
    ListNode* reverseKGroup(ListNode* tmp, int k) {
        stack<ListNode *> st ;
        ListNode* nextline = NULL ;
        ListNode* ret = tmp ;
        ListNode* nexttmp = NULL ;
        bool sta = true ;
        while (tmp)
        {
            st.push(tmp) ;
            tmp = tmp->next ;
            if (st.size() == k)
            {
                if (sta)
                {
                    ret = st.top() ;
                    sta = false ;
                }  
                else
                    nextline->next = st.top() ; 
                nexttmp = st.top() ;
                st.pop() ;
                while(! st.empty())
                {
                    nexttmp->next = st.top() ;
                    nexttmp = nexttmp->next ;
                    nexttmp->next = NULL ;
                    st.pop() ; 
                }
                nextline = nexttmp ;
            }  
        }
        while (! st.empty())
        {
            if (! nextline)
                break ;
            nextline->next = st.top() ;
            st.pop() ;
        }
        return ret ;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值