[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.


/* 整体思路:
 * 在反转链表的基础上,记录好左侧部分和右侧部分结点,然后和局部反转后的链表拼接起来即可
 */

/**
 * 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 || m < 1 || n < m)
            return NULL;
        ListNode* dummyHead = new ListNode(-1);
        dummyHead->next = head;
        ListNode* pCur = dummyHead;
        ListNode* pPre = NULL;
        ListNode* pNext = NULL;

        // 让pCur指向m结点的前一个结点,存储为left
        for (int i = 1; i <= m - 1; ++i)
            pCur = pCur->next;

        ListNode* left = pCur;

        // pCur指向m结点
        pCur = pCur->next;
        // 反转部分的尾结点存储为right
        ListNode* right = pCur;

        // 对m到n位置的数进行反转
        // 反转后这部分头结点为pPre
        // 尾结点需要事先存储为right
        // pNext为n右侧部分的头结点
        // right -> pNext
        // pPre接上m左侧部分 left->pPre
        // pNext接上n右侧部分
        for (int i = m; i <= n; ++i){
            pNext = pCur->next;
            pCur->next = pPre;
            pPre = pCur;
            pCur = pNext;
        }

        // left -> reverse part head: pPre -> ... -> reverse part tail:right ->pNext
        left->next = pPre;
        right->next = pNext;

        return dummyHead->next;
    }
};

// 这样写应该会更清晰
/**
 * 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* dummyHead = new ListNode(-1);
        dummyHead->next = head;

        // 1.记录第m个节点的前驱,left存储
        ListNode* pCur = dummyHead;
        for(int i = 1; i < m; ++i)
            pCur = pCur->next;
        ListNode* left = pCur;

        pCur = pCur->next;
        ListNode* right = pCur;

        // 2.翻转m --> n
        ListNode* pPre = NULL;
        ListNode* pNext = NULL;
        for(int i = m; i <= n; ++i){
            pNext = pCur->next;
            pCur->next = pPre;
            pPre = pCur;
            pCur = pNext;
        }

        // 3.连接:left->pPre->...->right->pCur
        left->next = pPre;
        right->next = pCur;
        return dummyHead->next;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值