赞
踩
链表如下: head -> 1, tail -> 8
1 -> 2 -> 3 -> 4 ->5 -> 6 -> 7 -> 8-> nullptr
K = 3
=>
1 -> 2 -> 5 -> 4 -> 3 -> 8 -> 7 -> 6 -> nullptr
(最后一部分小于K, 则不用再反转)
K = 4
=>
4 -> 3 -> 2 -> 1 -> 8 -> 7 -> 6 -> 5 -> nullptr
(head和tail都发生了变化)
#include <iostream> #include <algorithm> using namespace std; struct Node { int val; struct Node* next; }; struct Node* reverseLinkList(struct Node* head, struct Node* tail, struct Node* prev, struct Node* curr, int k, int idx) { static int offset = 0; static bool back = false; static struct Node* pre_group_last = nullptr; static struct Node* next_pre_group_last = nullptr; if (curr != tail && back != true) { reverseLinkList(head, tail, curr, curr->next, k, ++idx); } if (curr == tail) { back = true; offset = idx % k; pre_group_last = tail->next; next_pre_group_last = tail; tail->next = prev; return curr; } int j = idx - 1; bool b_section_end = j % k == (offset + 1) % k; bool b_first_section = j < k - offset; if (!b_section_end && !b_first_section) { curr->next = prev; } if (b_section_end) { curr->next = pre_group_last; pre_group_last = next_pre_group_last; if (b_first_section) { head = next_pre_group_last; } } if (j % k == offset) { next_pre_group_last = curr; } return head; } std::pair<struct Node*, struct Node*> makeLinkedList() { struct Node* tail = new Node{8, nullptr}; struct Node* n7 = new Node{7, tail}; struct Node* n6 = new Node{6, n7}; struct Node* n5 = new Node{5, n6}; struct Node* n4 = new Node{4, n5}; struct Node* n3 = new Node{3, n4}; struct Node* n2 = new Node{2, n3}; struct Node* head = new Node{1, n2}; return std::make_pair(head, tail); }; int main() { int k[] = {2, 3, 4, 5}; std::for_each(begin(k), end(k), [&](int i) { pair<struct Node*, struct Node*> list = makeLinkedList(); cout << "K =" << i << endl; cout << "before reverse: " << endl; for (struct Node* p = list.first; p != nullptr; p = p->next) cout << p->val << ", "; cout << endl; struct Node* head = reverseLinkList(list.first, list.second, nullptr, list.first, i, 0); cout << "after reverse: " << endl; for (struct Node* p = head; p != nullptr; p = p->next) { cout << p->val << ", "; } cout << endl; }); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。