1. 程式人生 > >Leetcode.25. Reverse Nodes in k-Group

Leetcode.25. Reverse Nodes in k-Group

null next cbc 有一點 邏輯 back 進行 hid ++

題意:鏈表翻轉,每k個翻一次,最後不足k個的不翻

題解:沒啥難點,就是要對邏輯有一點要求;當然你也可以先存到數組裏,然後用數學方法計算下標進行swap,但是這脫離了這道題的本意,代碼不放了

技術分享圖片
 1 class Solution {
 2 public:
 3     void reverse(vector<ListNode*>& lists) {
 4         for (auto i = 0; i < lists.size() - 1; i++) {
 5             ListNode *st = lists[i], *ed = lists[i + 1
]; 6 ListNode *cur = st, *nex = st->next, *tmp; 7 while (nex != ed) { 8 tmp = nex->next; 9 nex->next = cur; 10 cur = nex; 11 nex = tmp; 12 } 13 st = cur; 14 lists[i] = st;
15 } 16 for (auto i = 0; i < lists.size() - 1; i++) { 17 ListNode *st = lists[i], *ed = lists[i + 1]; 18 while (st->next->next != st) st = st->next; 19 st->next->next = ed; 20 } 21 return; 22 } 23 24 ListNode* reverseKGroup(ListNode* head, int
k) { 25 if (head == NULL || k <= 1) 26 return head; 27 vector<ListNode*> lists; 28 ListNode* p = head; 29 int cnt = 0; 30 while (p != NULL) 31 { 32 for (auto i = 0; i < k && p != NULL; i++) { 33 if (i == 0) 34 lists.push_back(p); 35 cnt++; 36 p = p->next; 37 } 38 } 39 if (cnt % k == 0) 40 lists.push_back(NULL); 41 reverse(lists); 42 return lists[0]; 43 } 44 };
View Code

Leetcode.25. Reverse Nodes in k-Group