92. Reverse Linked List II 翻转链表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() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* prem = dummy;
        //先找到第m个以及前一个
        for(int i=0;i<m-1;i++){
            prem = prem->next;
        }
        ListNode* cur = prem->next;
        //找到第n个以及后一个.
        ListNode* pren = dummy;
        for(int i=0;i<n;i++){
            pren = pren->next;
        }
        //翻转
        prem->next = reverse(cur,pren->next);
        //返回
        return dummy->next;
    }
    
    //@last 翻转链表的最后一个节点的后一个节点
    ListNode* reverse(ListNode* head,ListNode* last){
        ListNode *pre = last,*cur = head;
        while(cur != last){
            ListNode* Next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = Next;
        }
        return pre;
    }
    
};

 

posted on 2020-09-13 11:00  wsw_seu  阅读(80)  评论(0编辑  收藏  举报

导航