双指针
时间复杂度:
空间复杂度:
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param m int整型 * @param n int整型 * @return ListNode类 */ ListNode* reverseBetween(ListNode* head, int m, int n) { // write code here int cnt = 0; ListNode* dummyHead = new ListNode(-1); ListNode* p = dummyHead; p -> next = head; ListNode *pStart, *pEnd; while(p -> next!= NULL){ if(cnt == m - 1) pStart = p; if(cnt == n) pEnd = p; p = p -> next; cnt ++; } if(cnt == n) pEnd = p; //n为结尾的时候注意特例 ListNode* tail = pStart -> next; ListNode* nxtHead = pEnd -> next; pEnd -> next = NULL; reverseList(tail); pStart -> next = pEnd; tail -> next = nxtHead; return dummyHead -> next; } ListNode* reverseList(ListNode* head){ ListNode* pre = NULL; while(head != NULL){ ListNode* nxt = head -> next; head -> next = pre; pre = head; head = nxt; } return pre; } };