Leetcode 之 Reverse Linked List II

本文介绍了一种在链表中从位置m到n进行原地、单次遍历反转的方法,并提供了一个20ms的C++实现示例。

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

原题:

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given 1->2->3->4->5->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

这个题比较简单,就是把第m到n个元素倒转过来。。。。看到这个题第一反应用来解决。。。

而且为了方便,其实在很多链表的相关实现时,都可以声明一个ListNode*叫做pre,pre的next指向head

基本思想:

1 把current一直向后,直到current的next要入栈

2 current的next开始,入栈m-n+1个元素

3 出栈,current的next指向栈顶,最后把current指向tail,即栈里最后一个元素的next指向tail


代码(20ms):

class Solution {
public:
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        ListNode * pre = new ListNode(-1);
        pre->next = head;
        
        //pre指向head的前一个
        ListNode *current = pre;
        
        //把current指向第m个元素的前一个
        for(int i = 0 ;i < m-1 ;i++){
            current = current->next;
        }
        
        ListNode * tail = current->next;
        stack<ListNode*>s;
        
        //把第m到n个元素都入栈
        //tail最后指向第n个元素的next
        for(int i = 0 ; i <= n-m ;i++){
            ListNode* temp = tail;
            s.push(temp);
            tail = tail->next;
        }
        //把current指向栈顶
        for(int i = 0; i<= n-m;i++){
            current->next = s.top();
            s.pop();
            current = current->next;
        }
        //current的next指向原来第n个元素的next
        current->next = tail;

        
        return (pre->next);
        
        
        
    }
};

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值