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

 

解题思路:

这里要求翻转第m个节点到第n个节点的顺序。

我们可以先通过m与n之间的距离(n-m)确定一个滑动窗口:头节点为start,尾节点为end,然后再根据m来找到窗口具体的起始位置

现将块的头尾翻转,即:

start->next = end->next;

pre(头节点的前一个节点)-> next = end

需要注意的是!

边界情况当m等于1时!我们可以吧head直接指到end节点。

代码:

/**
 * 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 || (m == n))
            return head;
        ListNode *start = head;
        ListNode *end = head;
        ListNode *p = head;
        int diff = n - m;
        while(diff){
            p = p->next;
            diff--;
        }
        start = head;
        end = p;
        ListNode *pre = start;
        for(int i = 1; i < m; i++){
            pre = start;
            start = start->next;
            end = end->next;
        }
        ListNode* nextN = end->next;
        //start to reverse
        if(m == 1){
            head = end;   
        }else{
            pre->next = end;
        }
        p = start->next;
        pre = start;
        start->next = nextN;
        
        while(p != nextN){
            ListNode* temp = p->next;
            p->next = pre;
            pre = p;
            p = temp;
        }
        return head;
    }
};

 

posted @ 2018-06-05 12:15  妖域大都督  阅读(77)  评论(0编辑  收藏  举报