1. 程式人生 > 實用技巧 >25. K 個一組翻轉連結串列

25. K 個一組翻轉連結串列

25. K 個一組翻轉連結串列

難度困難651給你一個連結串列,每 k 個節點一組進行翻轉,請你返回翻轉後的連結串列。 k 是一個正整數,它的值小於或等於連結串列的長度。 如果節點總數不是 k 的整數倍,那麼請將最後剩餘的節點保持原有順序。 示例: 給你這個連結串列:1->2->3->4->5 當 k = 2 時,應當返回: 2->1->4->3->5 當 k = 3 時,應當返回: 3->2->1->4->5 思路:新增啞巴節點,即虛擬 head 節點 head_res 節省程式碼量。 程式碼:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 
*/ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode *current, *after, *head_res, *first, *temp, *pre; current = head;//current = 1 if(k==1||head==NULL||head->next==NULL) return head; head_res = new ListNode; head_res
->next = head; pre = head_res; int size = 0; current = head; while(current!=NULL) { current = current->next; size++; } int i, j; for(j = 1; j <= size/k; j++) { current = pre->next; //current = 3
after = current->next; //after = 4 first = current; //first = 3 for(i = 1; i <= k-1; i++) { temp = after->next;//temp = 5 after->next = current;//4->3 current = after;//current = 4 after = temp;//after = 5 } pre->next = current;//1->3 first->next = after;//3->5 pre = first;//pre = 3 } return head_res->next; delete(head_res); } };