题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
http://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ ListNode* reverseKGroup(ListNode* head, int k) { ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* pre = dummy; ListNode* end = dummy; while(end->next){ for(int i=0; i<k&&end!=nullptr; i++){ end = end->next; } if(!end) break; ListNode* start = pre->next; ListNode* next = end->next; end->next = nullptr; pre->next = reverse(start); start->next = next; pre = start; end = pre; } return dummy->next; // write code here } ListNode* reverse(ListNode* head){ ListNode* pre = nullptr; ListNode* cur = head; while(cur){ ListNode* t = cur->next; cur->next = pre; pre = cur; cur = t; } return pre; } };
https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/tu-jie-kge-yi-zu-fan-zhuan-lian-biao-by-user7208t/