题解 | #每K个一组反转链表#
每K个一组反转链表
https://www.nowcoder.com/practice/a632ec91a4524773b8af8694a51109e7
#include <iostream> #include <stack> using namespace std; struct LinkNode { int value; LinkNode *next; LinkNode(int x) { value = x; next = NULL; } LinkNode() { next = NULL; } }; LinkNode *head = new LinkNode(); LinkNode *tail = head; int len = 0; void add(int x) { LinkNode *tmp = new LinkNode(x); tail->next = tmp; tail = tail->next; len++; } int main() { int x; while (cin >> x) { add(x); if (cin.get() == '\n') break; } int k; cin >> k; stack<int>s; for (int i = 0; i < len / k; i++) { for (int j = 0; j < k; j++) { s.push(head->next->value); head = head->next; } while (!s.empty()) { cout << s.top() << " "; s.pop(); } } while (head->next) { cout << head->next->value<<" "; head = head->next; } } // 64 位输出请用 printf("%lld")