#include <iostream> using namespace std; struct ListNode { int val; struct ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; void printLink(ListNode* head) { ListNode* p = head; while (p != nullptr) { cout << p->val << " "; p = p->next; } cout << endl; } ListNode* reverseNode(ListNode* head) { ListNode* pre = nullptr; ListNode* cur = head; ListNode* nex = nullptr; while (cur) { nex = cur->next; cur->next = pre; pre = cur; cur = nex; } return pre; } ListNode* reverseKGroup(ListNode* head, int k) { // write code here ListNode* dummy = head; ListNode* pre = dummy, * end = dummy; while (end->next != NULL) { for (int i = 0; i < k && end; i++) end = end->next; if (end == nullptr) break;//使end循环向后,指向最后一个 ListNode* start = pre->next; ListNode* endNextNode = end->next; end->next = nullptr; pre->next = reverseNode(start); start->next = endNextNode; pre = end = start; } return dummy->next; } int main() { int a = 0, k = 0, n = 0; ListNode* linkdata = new ListNode(0); ListNode* tmp = nullptr; ListNode* tail = linkdata; ListNode* ans = nullptr; while (true) { cin >> a; tmp = new ListNode(a); tail->next = tmp; tail = tail->next; n += 1; if (cin.get() == '\n') { break; } } cin >> k; ans = reverseKGroup(linkdata, k); printLink(ans); return 0; } // 64 位输出请用 printf("%lld")