基础题,考察反转单链表。需要注意细节处理。
用了一个while遍历链表,常熟个变量存放数据。时间复杂度O(n),空间复杂度O(1)。满足题目要求。
/** * 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 if(n == 1 || m == n){ return head; } ListNode* p = head; ListNode* before = nullptr; ListNode* after = nullptr; ListNode* pre = nullptr; ListNode* front = nullptr; ListNode* back = nullptr; int i = 0; m--; n--; while(p){ if(i == m - 1){ before = p; } else if(i == n + 1){ after = p; } if(i == m){ front = p; } else if(i == n){ back = p; } if(i > m && i <= n){ ListNode* temp = p; p = p->next; temp->next = pre; pre = temp; } else { pre = p; p = p->next; } i++; } if(before){ before->next = back; } else{ head = back; } front->next = after; return head; } };