码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-algorithms-92. Reverse Linked List II

时间:2019-06-01 23:17:25      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:def   from   val   复杂   not   note   list   example   ebe   

leetcode-algorithms-92. Reverse Linked List II

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

解法

/**
 * 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 d(-1);
        d.next = head;
        ListNode *pre_first = &d;
        for (int i = 1; i < m; ++i) {
            pre_first = pre_first->next;
        }
        
        ListNode *first = pre_first->next;
        ListNode *second;
        ListNode *second_last;
        if (first->next != nullptr)
            second = first->next;
        
        for (int i = 0; i < n - m; ++i) {
            second_last = second->next;
            second->next = pre_first->next;
            pre_first->next = second;
            first->next = second_last;
            second = second_last;
        }
        
        return d.next;  
    }
};

时间复杂度: O(n),n 反转的的结点 index 值。

空间复杂度: O(1)。

leetcode-algorithms-92. Reverse Linked List II

标签:def   from   val   复杂   not   note   list   example   ebe   

原文地址:https://www.cnblogs.com/mathli/p/10961246.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!