题解 | #链表中的节点每k个一组翻转(又臭又长版)#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * ListNode(int x) : val(x), next(nullptr) {} * }; */ class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { if (head == nullptr) return head; bool reverseflag = true; ListNode* res = nullptr; ListNode* p1 = head; vector<ListNode*> listvector; while (true) { cout << "p1:" << p1->val << endl; ListNode* cur = p1; //判断是否反转 ListNode* cur1 = p1; int j = 0; for (int i = 0; i < k - 1; i++) { if (cur1 -> next != nullptr) cur1 = cur1->next; else break; j++; } if (j == k - 1) reverseflag = true; else reverseflag = false; res = nullptr; if (reverseflag) { for (int i = 0; i < k; i++) { ListNode* newnode = new ListNode(cur->val); newnode->next = res; res = newnode; cur = cur->next; } } else { res = p1; } listvector.push_back(res); for (int i = 0; i < k; i++) { p1 = p1->next; if (p1 == nullptr) break; } if (p1 == nullptr) break; } for (int i = 0; i < listvector.size() - 1; i++) { ListNode* temp = listvector[i]; ListNode* temp1 = listvector[i + 1]; while (temp->next != nullptr) { temp = temp->next; } temp->next = temp1; } res = listvector[0]; return res; } };