LeetCode 25. k个一组翻转链表
程序员文章站
2022-03-18 09:32:55
...
题目描述
解题思路
分别求解并合并
分成若干个K个一段的,然后将每个进行翻转,最后将他们连接起来即可。
代码实现
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* rev(ListNode* head)
{
if(head == NULL || head->next == NULL) return head;
ListNode* p = head, *q = p->next, *r;
while(q != NULL)
{
r = q->next;
q->next = p;
p = q;
q = r;
}
return p;
}
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode* fast = head, *re = head, *pre = NULL;
int length = 0;
while(length++ != k)
{
if(fast == NULL) return head;
pre = fast;
fast = fast->next;
}
pre->next = NULL;
re = rev(head);
head->next = reverseKGroup(fast, k);
return re;
}
};