leetcode 链表# 92. Reverse Linked List II

92. Reverse Linked List II

标签: leetcode list

Qustion

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.


关键:抓住变化的那个结点,以及注意循环次数,防止访问NULL地址

解题思路

  1. 定位到前结点nodePre
  2. 记录要插入的最前面的结点childListBegin,和revert list的最后一个结点childListEnd
  3. 在这两处进行操作
    nodeA = childListEnd->next;
    childListEnd->next = nodeA->next;
    nodeA->next = childListBegin;
    childListBegin = nodeA;

代码如下:

/**
 * 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) return head;
        if (m == n) return head;

        ListNode *childListBegin, *childListEnd, *nodeA, *nodeB, *nodePre;

        for (int i = 0, nodePre = NULL; i < m - 2; ++i)
        {
            nodePre = nodePre->next;
        }

        nodeA = (nodePre) ? nodePre->next : head;
        nodeB = nodeA->next;

        nodeA->next = nodeB->next;
        nodeB->next = nodeA;

        childListBegin = nodeB;
        childListEnd = nodeA;

        int count = n - m;
        for (int i = 0; i <  count - 1; ++i)
        {
            nodeA = childListEnd->next;
            childListEnd->next = nodeA->next;
            nodeA->next = childListBegin;
            childListBegin = nodeA;
        }

        if (nodePre)
        {
            nodePre->next = childListBegin;
        }
        
        if (m == 1) {
            return childListBegin;
        }
        
        return head;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,771评论 0 33
  • 今天差不多八点多起来的吧,心血来潮想去教室学习啦/小纠结。去623还伞,正好有个同学也要出去学习,于是就一块出...
    永恒yxh阅读 190评论 0 1
  • 傍晚停电了。 我们刚煮熟了面片,等着炒好菜一和就可以吃一顿香喷喷的炒面片了。可是面还没捞出来就停电了。 出去买了扎...
    阿颖果阅读 104评论 0 0