025 K个一组翻转链表

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值