面试的时候居然写炸了。补一下
1 #include <iostream> 2 3 using namespace std; 4 5 struct ListNode { 6 int val; 7 ListNode *next; 8 ListNode() : val(0), next(nullptr) {} 9 ListNode(int x) : val(x), next(nullptr) {} 10 ListNode(int x, ListNode *next) : val(x), next(next) {} 11 }; 12 13 class Solution { 14 public: 15 std::pair<ListNode *, ListNode *> reverse(ListNode *start, ListNode *end) { 16 cout << "reverse(" << start->val << ", " << end->val << ")" << endl; 17 ListNode *pre = end->next, *pos = start, *next = start->next; 18 auto x = end->next; 19 while (pos != x) { 20 next = pos->next; 21 pos->next = pre; 22 pre = pos; 23 pos = next; 24 } 25 return { end, start }; 26 } 27 28 ListNode* reverseKGroup(ListNode* head, int k) { 29 int n = 0; 30 ListNode *res = nullptr, *p = head, *start = head, *tmp = nullptr; 31 while (p != nullptr) { 32 n++; 33 if (n == k) { 34 n = 0; 35 auto se = reverse(start, p); 36 p = start = se.second->next; 37 if (tmp != nullptr) { 38 tmp->next = se.first; 39 } 40 tmp = se.second; 41 if (res == nullptr) res = se.first; 42 } 43 else { 44 p = p->next; 45 } 46 } 47 return res; 48 } 49 }; 50 51 void print(ListNode *p) 52 { 53 while (p != nullptr) { 54 cout << p->val << ' '; 55 p = p->next; 56 } 57 cout << "NULL " << endl; 58 } 59 60 int main() 61 { 62 ListNode *node = new ListNode(1); 63 ListNode *node1 = new ListNode(2); 64 ListNode *node2 = new ListNode(3); 65 ListNode *node3 = new ListNode(4); 66 ListNode *node4 = new ListNode(5); 67 ListNode *node5 = new ListNode(6); 68 69 node->next = node1; 70 node1->next = node2; 71 node2->next = node3; 72 node3->next = node4; 73 node4->next = node5; 74 node5->next = nullptr; 75 76 Solution s; 77 78 print(s.reverseKGroup(node, 2)); 79 80 int xyz; 81 cin >> xyz; 82 83 return 0; 84 }