链表内指定区间反转_牛客题霸_牛客网
ListNode* reverseList(ListNode* head, ListNode* tail) {ListNode* pre = nullptr;ListNode* cur = head;while (cur != tail) { 最后cur就是tailListNode* temp = cur->next;cur->next = pre;pre = cur;cur = temp;}return pre;}ListNode* reverseBetween(ListNode* head, int m, int n) {ListNode* dummyNode = new ListNode(0);dummyNode->next = head;ListNode* pre = dummyNode;for (int i = 1; i < m; i++) {pre = pre->next;}ListNode* start = pre->next;ListNode* end = pre->next;for (int i = m; i <= n; i++) {end = end->next;}pre->next = reverseList(start, end);//执行这个函数以后start变成传过去的链表的尾节点,所以直接连接start和end就行start->next = end;return dummyNode->next;}
链表中的节点每k个一组翻转_牛客题霸_牛客网
ListNode* reverseList(ListNode* head, ListNode* tail) {ListNode* pre = nullptr;ListNode* cur = head;while (cur != tail) {ListNode* temp = cur->next;cur->next = pre;pre = cur;cur = temp;}return pre;}ListNode* reverseKGroup(ListNode* head, int k) {// write code hereif (k == 1 || head->next == nullptr || head == nullptr) return head;ListNode* dummy = new ListNode(0);dummy->next = head;ListNode* pre = dummy;ListNode* start = pre->next;ListNode* end = pre;while (end->next != nullptr && end != nullptr) {start = pre->next;end = pre;int i;for (i = 0; i <= k; i++) {if (end->next) end = end->next;else {end = nullptr;break;}}if (i < k) break;else {pre->next = reverseList(start, end);start->next = end;pre = start;}}return dummy->next;}