#Leetcode# 92. Reverse Linked List II

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 92. Reverse Linked List II相关的知识,希望对你有一定的参考价值。

https://leetcode.com/problems/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) {
        if(!head) return NULL;
        int num = m - 1;
        ListNode *dummy = new ListNode(-1);
        ListNode *st = dummy, *ans = st;;
        dummy -> next = head;
        ListNode *slow = head;
        n -= m, m -= 1;
        while(m --) slow = slow -> next;
        ListNode *cur = slow;
        while(n --) cur = cur -> next;
        ListNode *end = cur -> next;
        cur -> next = NULL;
        slow = reverseList(slow);
        ListNode *fast = slow;
        while(fast -> next) fast = fast -> next;
        fast -> next = end;
        while(num --) st = st -> next;
        st -> next = slow;
        return ans -> next;
    }
    
    ListNode *reverseList(ListNode *c) {
        if(!c || !c -> next) return c;
        ListNode *New = reverseList(c -> next);
        c -> next -> next = c;
        c -> next = NULL;
        return New;
    }
};

  分三段 然后拼在一起 但是写的乱糟糟 大概写了一个多小时 我恨!自己不争气 落泪

FH

以上是关于#Leetcode# 92. Reverse Linked List II的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode92]Reverse Linked List II

#Leetcode# 92. Reverse Linked List II

Leetcode 92. Reverse Linked List II

leetcode.92. Reverse Linked List II

[LeetCode]92. Reverse Linked List II

LeetCode 92. Reverse Linked List II