Leetcode 25 k个一组翻转链表Reverse Nodes in k-Group

题目:
Reverse Nodes in k-Group

在组内作反转

Given the head of a linked list, reverse the nodes of the list k at a time, and return the modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

//思路:递归思想:
//先把它成k段,每一段k段里面做反转操作,
//(先递归,直接到最后一段,递归是分段找的是每一段的最后一个节点)

var reverseKGroup = function(head, k) {
    let count=0;
    current=head;//每一段的开头
    while(current!==null && count!==k){
        current=current.next;
        count++;
    } //最后的current是下一段的起点

    if(count==k){   //现在得到当前段的开头head 和 下一段的开头 current,做反转操作
        current = reverseKGroup(current, k);
        while(count>0){
        let next=head.next;
        head.next=current;
        current=head;
        head=next;
        count--;
        }
        head=current; //以为head一直移动到最后的null
    }
    return head;//如果不够k,则直接返回 !!注意head是不动的,一直动的是current
}


//总结:一段链表 反转接到另一段链表的 ,即找每一段链表的开头节点,然后做反转
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值