思路很简单,首先得有一个辅助函数,将链表head到tail之间的部分翻转。这个函数用递归写起来很简单,并且容易理解,强烈推荐!然后就是用两个p,q指针不停滑动翻转链表的事情了,记住我们需要把p的前驱pre记下来,不然翻转以后就连不上了。
/**
* 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 (!head)
return head;
ListNode *fake = new ListNode(-1);
fake->next = head;
ListNode *pre = fake, *p = head, *q = head;
int i = 1;
while (q != NULL && i < k) {
i++;
q = q->next;
}
while (q != NULL) {
ListNode *q_next = q->next;
helper(p, q);
pre->next = q;
p->next = q_next;
swap(p, q);
pre = q;
i = 0;
while (q != NULL && i < k) {
p = p->next;
q = q->next;
i++;
}
}
return fake->next;
}
void helper(ListNode *head, ListNode *tail) {
if (head == tail)
return;
helper(head->next, tail);
head->next->next = head;
head->next = NULL;
}
};
http://oj.leetcode.com/problems/reverse-nodes-in-k-group/
本文介绍了一种使用递归辅助函数实现链表K组翻转的方法。通过定义辅助函数来翻转从head到tail之间的链表部分,并利用双指针技巧完成整个链表的翻转任务。
443

被折叠的 条评论
为什么被折叠?



