思路:利用棧的特性,K個節點壓入棧中依次彈出組成新的鏈表,不夠K個節點則保持不變
/*** struct ListNode {* int val;* struct ListNode *next;* ListNode(int x) : val(x), next(nullptr) {}* };*/
#include <stack>
class Solution {
public:/*** 代碼中的類名、方法名、參數名已經指定,請勿修改,直接返回方法規定的值即可** * @param head ListNode類 * @param k int整型 * @return ListNode類*/ListNode* reverseKGroup(ListNode* head, int k) {// write code herestack<ListNode*> sk;//用來保存鏈表節點ListNode* temp = head;ListNode* ret = new ListNode(-1);ListNode* ret1 = ret;//按k個節點一次一次去遍歷鏈表while(1){int count = k;//K個節點之內依次push入棧中while(count&&temp){sk.push(temp);temp = temp->next;count--;}//如果push完了還不夠數量則該次不需要反轉鏈表反轉保持原型進行鏈接,從而跳出循環if(count){//下一階段的第一個節點ret1->next = head;//這句不能省略的原因是如果k大于鏈表的長度,沒有這句話return結果為空,但是應該是該鏈表break;}//如果夠數量則從棧中彈出加入結果鏈表中while(!sk.empty()){ret1->next = sk.top();sk.pop();ret1 = ret1->next;}//結果鏈表的下一節點指向后面的鏈表ret1->next = temp;head = temp;} return ret->next;}
};