[leetcode] 92.Reverse Linked List II

链表翻转指定区间
本文介绍了如何在链表中实现指定区间的翻转操作,包括核心思路、代码实现及注意事项。

题目:
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->NULL, m = 2 and n = 4,

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

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
题意:
给定一个链表,翻转从第m个元素到第n个元素。
思路:
做这道题目需要比较细心,翻转后的那部分必须与它的前后部分连接起来。我们需要找到第一个需要翻转节点的前一个节点记作before_first,并且找到需要翻转的最后一个节点,那么翻转后before_first应该链接上这个节点。并且待翻转的第一个节点需要指向待翻转的最后一个节点的下一个节点。
以上。
代码如下:

/**
 * 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) {
        if (head == NULL || head->next == NULL || m == 0 || n == 0 || m == n)return head;
        ListNode* first = head, *second, *before_first = NULL, *res = head;
        for (int i = 0; i < m - 1; i++) {
            before_first = first;
            first = first->next;
        }

        second = first->next;
        for (int i = m; i < n - 1; i++)
            second = second->next;


        if (before_first != NULL)before_first->next = second;
        else res = second;

        ListNode* next;
        before_first = first;
        first = first->next;
        before_first->next = second->next;


        while (first != second) {
            next = first->next;
            first->next = before_first;
            before_first = first;
            first = next;
        }
        first->next = before_first;
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值