1957

无聊蛋疼的1957写的低端博客
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

[leetcode]Reverse Linked List II

Posted on 2014-01-08 09:17  1957  阅读(576)  评论(0编辑  收藏  举报

= =简单题...

尝试考虑了各种情况...

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *reverse(ListNode* start){
        ListNode* prev = nullptr;
        ListNode* now = start;
        while(now != nullptr){
            ListNode* next = now -> next;
            now -> next = prev;
            prev = now;
            now = next;
        }
        return prev;
    }
    ListNode *reverseBetween(ListNode *head, int m, int n) {
        if(m == n) return head;
        if(head == nullptr) return head;
        
        int cnt = 1;
        ListNode* prev = nullptr;
        ListNode* breakNode = head;
        // m is head
        while(cnt < m){
            prev = breakNode;
            breakNode = breakNode -> next;
            cnt ++;
        }
        ListNode* last = breakNode;
        cnt = n - m; // pre of last
        //last is tail
        while(cnt > 0){
            last = last -> next;
            cnt --;
        }
        //do reverse
        ListNode* next = last -> next;
        last -> next = nullptr;
        ListNode * newList = reverse(breakNode);
        if(prev){
            prev -> next = newList;
        }else{
            head = newList;
        }
        breakNode -> next = next;
        return head;
    }
};