题解 | #链表中的节点每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) { // write code here if (head == nullptr || head->next == nullptr) { return head; } stack<int>s1; ListNode* newhead = head; ListNode* newhead1 = head; while (head != nullptr) { for (int i = 0; i < k; i++) { if (head == nullptr) { return newhead1; } s1.push(head->val); head = head->next; } if (s1.size() == k) { for (int i = 0; i < k; i++) { newhead->val = s1.top(); s1.pop(); newhead = newhead->next; } } } return newhead1; } };
思想:用栈实现反转。每k个入栈 s1.push(head->val);,然后出栈组合链表 newhead->val = s1.top();。在这个过程中head=head->next;一直往后。当第一组k个处理完,head变成第k+1个。newhead是为了出栈后组合。newhead1是为了保留原始头节点位置。 if (s1.size() == k) 加的判断,是为了最后一组可能不足k时,不需要进行处理。