基本思想是對每k個節點採用頭插法,時間複雜度爲O(n)。
C++代碼:
#include <vector>
#include <iostream>
using namespace std;
/**
* 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<2 || NULL == head || NULL == head->next)
return head;
//res->next記錄返回結果
ListNode * res = new ListNode(-1);
res->next = head;
//last_tail記錄上一次對k個節點進行操作後的最後一個節點
ListNode * last_tail = res;
while(1)
{
//找t_head之後是否有k個節點
int n = 0;
// ListNode *num_p = t_head;
ListNode *num_p = last_tail->next;
while(num_p && n != k)
{
++n;
num_p = num_p->next;
}
//如果n等於k,則num_p爲下一組的首節點的指針
//不足k個節點,返回結果
if(n != k)
{
ListNode * t = res->next;
delete res;
return t;
}
//n == k
else
{
//pre記錄待插入節點的上一個節點
ListNode *pre = last_tail->next;
//cur記錄當前待插入的節點
ListNode *cur = pre->next;
//此時num_p爲以t_head開頭的第k+1個節點
//將當前待插入的節點插到last_tail的後面
while (cur != num_p)
{
pre->next = cur->next;
cur->next = last_tail->next;
last_tail->next = cur;
//指針後移
cur = pre->next;
}
//k個節點插入完畢後,更新last_tail到當前操作的k個節點的最後一個節點
last_tail = pre;
}
}
}
};
int main()
{
Solution s;
ListNode *head, *p;
head = NULL;
for (int i=7;i>0;--i)
{
p = new ListNode(i);
p->next = head;
head = p;
}
ListNode *res = s.reverseKGroup(head, 3);
p = res;
while(p)
{
cout<<p->val<<'\t';
p = p->next;
}
return 0;
}