LeetCode-25:Reverse Nodes in k-Group (以k大小的組翻轉連結串列)
阿新 • • 發佈:2019-01-01
題目:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
例子:
Example 1:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
- Only constant extra memory is allowed.
- You may not alter the values in the list’s nodes, only nodes itself may be changed.
問題解析:
給定單向連結串列,以k個節點作為一組進行連結串列的翻轉。如果剩下的節點不滿k個,則不進行翻轉。
連結:
思路標籤
分步進行:先統計,後翻轉
解答:
- 題目其實不難,關鍵是理清楚翻轉的操作,以及所需要的節點;
- 首先統計後面的節點是否滿足k個作為一組進行翻轉,若不滿足則不進行翻轉;
- 注意每次都需要記錄前一個翻轉組的最後一個節點,進而與下一組的翻連結串列進行連線;
- 注意,返回的連結串列的頭節點是記錄第一組翻轉後的頭節點,與後面的無關,或者如果沒有一組進行過翻轉,則直接返回原始連結串列頭節點。
/**
* 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) {
if (k == 1 || head == nullptr)
return head;
ListNode *pHead = head;
ListNode *pNode = head;
ListNode *pTailPrevious = pNode;
int first = true;
while(pNode != nullptr){
ListNode *pTail = pNode;
int n = 1;
// 統計後面是否還存在k個節點
while(pNode != nullptr && n <= k){
pNode = pNode->next;
n++;
}
// 如果還存在k個節點則進行翻轉並對該k個節點翻轉連結串列與之前的進行連線,否則不進行翻轉直接連線。
if(n > k){
pNode = pTail;
ListNode *pPrevious = nullptr;
n = 1;
while(n <= k){
ListNode *pNext = pNode->next;
pNode->next = pPrevious;
pPrevious = pNode;
pNode = pNext;
n++;
}
// 判斷是否是第一段,第一段的翻轉節點為最後的頭節點
if(first == true){
pHead = pPrevious;
pTailPrevious = pTail;
first = false;
}else{
pTailPrevious->next = pPrevious;
pTailPrevious = pTail;
}
}else{
// 如果還是第一段則說明不足k個,直接返回連結串列
if(first == true){
return pHead;
}
pTailPrevious->next = pTail;
}
}
return pHead;
}
};