= =简单题...
尝试考虑了各种情况...
/** * 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; } };
by 1957