#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;
    }
};

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

 

posted @ 2019-02-20 21:10  丧心病狂工科女  阅读(118)  评论(0编辑  收藏  举报