題目連接html
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.node
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.函數
You may not alter the values in the nodes, only nodes itself may be changed.this
Only constant memory is allowed.code
For example,
Given this linked list: 1->2->3->4->5
htm
For k = 2, you should return: 2->1->4->3->5
blog
For k = 3, you should return: 3->2->1->4->5
ip
每次選取好一個group後,調用翻轉鏈表子函數翻轉該groupleetcode
/** * 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 tmphead(0); ListNode *p = head, *tail = &tmphead;//tail 爲當前已經處理完的尾節點 while(p) { ListNode *groupHead = p; int i = 1; for(i = 1; i < k && p->next != NULL; i++)p = p->next; if(i != k){tail->next = groupHead; return tmphead.next;}//最後不足k個節點 p = p->next; pair<ListNode*, ListNode*>ht = reverseList(groupHead, p); tail->next = ht.first; tail = ht.second; } return tmphead.next; } //翻轉鏈表,並返回翻轉後鏈表的頭結點和尾節點 pair<ListNode*, ListNode*> reverseList(ListNode* head, ListNode *end) { ListNode *p = head, *newHead = NULL; while(p != end) { ListNode *tmp = p->next; p->next = newHead; newHead = p; p = tmp; } return make_pair(newHead, head); } };
上面的方法實際上遍歷了2遍鏈表,能夠稍加改進在計數k個鏈表的過程當中就開始翻轉, 最後部分若是不足k個節點,則還原原來的順序 本文地址rem
/** * 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 tmphead(0); ListNode *p = head, *tail = &tmphead;//tail 爲當前已經處理完的尾節點 while(p) { pair<ListNode*, ListNode*>ht = reverseList(p,k); tail->next = ht.first; tail = ht.second; p = tail->next; } return tmphead.next; } //翻轉從head開始的k個鏈表節點,若是不足k個則不翻轉,返回翻轉後的這k個節點 //子鏈表的head和tail。翻轉後的子鏈表仍是和子鏈表後面的部分相連的。 pair<ListNode*, ListNode*> reverseList(ListNode* head, int k) { ListNode *p = head, *newHead = NULL; int cnt = 0; while(p && cnt < k) { ListNode *tmp = p->next; p->next = newHead; newHead = p; p = tmp; cnt++; } head->next = p;//把翻轉後的子鏈表和子鏈表後面的部分連起來 if(cnt == k) return make_pair(newHead, head); else return reverseList(newHead, cnt);//不足k個,還原原來的順序 } };
【版權聲明】轉載請註明出處:http://www.cnblogs.com/TenosDoIt/p/3794505.html