92. Reverse Linked List II

本文介绍了一种在一过式中反转链表指定区间的高效算法,详细解析了核心代码逻辑,通过实例展示了从位置m到n的链表部分如何被反转,适用于1≤ m ≤ n ≤链表长度的情况。

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

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

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

AC code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* dummy = new ListNode(0);
        ListNode* pre = new ListNode(0);
        ListNode* cur = new ListNode(0);
        dummy->next = head;
        pre = dummy;
        cur = dummy->next;
        for (int i = 1; i < m; ++i) {
            pre = pre->next;
            cur = cur->next;
        }
        for (int i = 0; i < n-m; ++i) {
            ListNode* temp = cur->next;
            cur->next = temp->next;
            temp->next = pre->next;
            pre->next = temp;
        }
        return dummy->next;
    }
};

Runtime: 0 ms, faster than 100.00% of C++ online submissions for Reverse Linked List II.

 

core code:

for (int i = 0; i < n-m; ++i) {
    ListNode* temp = cur->next;
    cur->next = temp->next;
    temp->next = pre->next;
    pre->next = temp;
 }

step 1:

  

1  2  3  4  5

pre

  cur

     temp

cur->next = temp->next;  2  ->  4
temp->next = pre->next;  3  ->  2
pre->next = temp;      1  ->  3

   

step 2:

 

1  2  3  4  5

pre

  cur

         temp

cur->next = temp->next;  2  ->  5
temp->next = pre->next;  4  ->  3
pre->next = temp;      1  ->  4

 

转载于:https://www.cnblogs.com/ruruozhenhao/p/9867143.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值