LeetCode 第二十五题 K个一组翻转链表
给出一个链表,每 k 个节点一组进行翻转,并返回翻转后的链表。
k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k
的整数倍,那么将最后剩余节点保持原有顺序。
示例 :
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
说明 :
你的算法只能使用常数的额外空间。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
在这里我们参考了网址中的解题步骤,先找到前K个节点,将其翻转,剩下的结点,使用递归的方法进行处理。前K个节点翻转算法,是将头节点从链表中切掉,放在当前链表的末端,切除K次,即可将链表翻转。代码如下所示:
Java
public ListNode reverseKGroup(ListNode head, int k) {
ListNode current_node = head;
int count = 0;
while (current_node != null && count != k) {
current_node = current_node.next;
count++;
}
if (count == k) {
current_node = reverseKGroup(current_node, k);/// 递归的解决子问题
while (count-- > 0) {
ListNode temp = head.next;
head.next = current_node;
current_node = head;
head = temp;
}///最终,该段的所有节点将会截空,head应指向current_node
head = current_node;
}
return head;
}
C++
class Solution
{
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode* current_node=head;
int count_node=0;
while(current_node!=NULL&&count_node!=k)
{
count_node++;
current_node=current_node->next;
}
if(count_node==k)
{
current_node=reverseKGroup(current_node,k);
while(count_node-->0)
{
ListNode* temp=head->next;
head->next=current_node;
current_node=head;
head=temp;
}
head=current_node;
}
return head;
}
};
Python
class Solution(object):
def reverseKGroup(self, head, k):
current_node = head
count_node = 0
while current_node and count_node != k:
current_node = current_node.next
count_node += 1
if count_node == k:
current_node = self.reverseKGroup(current_node, k)
while count_node > 0:
temp_node = head.next
head.next = current_node
current_node = head
head = temp_node
count_node -= 1
head = current_node
return head