Leetcode 92 Reverse Linked List II

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010821666/article/details/82749459

##Leetcode 92 Reverse Linked List II

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 || !head->next || m >= n)
            return head;
        ListNode* pre = nullptr;
        ListNode* next = nullptr;
        ListNode* preHead = new ListNode(0);
        preHead->next = head;
        ListNode* newHead = preHead;
        int count = 0;
        while(newHead->next && count<m-1) {
            newHead = newHead->next;
            count ++;
        }
        ListNode* former =newHead;//连接翻转部分的头
        newHead = newHead->next;
        ListNode* latter = newHead;//翻转部分的尾


        while(newHead->next && count<n-1){
            next = newHead->next;
            newHead->next = pre;
            pre = newHead;
            newHead = next;
            count ++;
        }
        if(!newHead->next){
            newHead->next = pre;
            former->next = newHead;
            return preHead->next;//it is important!!!
        }else{
            next = newHead->next;
            newHead->next = pre;
            former->next = newHead;
            latter->next = next;
            return preHead->next;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/u010821666/article/details/82749459