黄金挑战 | K个一组反转

1.头插法

思路:

1.先遍历链表得出链表长度len,确定分组n = len/k

2.按分组进行反转

public ListNode reverseKGroup(ListNode head,int k){
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    ListNode cur = head;
    int len = 0;
    while(cur != null){
        len++;
        cur = cur.next;
    }
    int n = len / k;
    ListNode pre = dummy;
    cur = head;
    for(int i = 0; i < n ;i++){
        for(int j = 0;j < k - 1;j++){
            ListNode next = cur.next;
            cur.next = cur.next.next;
            next.next = pre.next;
            pre.next = next;
        }
        pre = cur;
        cur = cur.next;
    }
    return dummy.next;
}

2.穿针引线法

1.因为要分组反转,所以要一组一组处理,将其分为已反转,正在反转,等待反转三个部分,同时,为了方便头节点的处理,新建一个虚拟节点。

2.遍历,根据是否为K个找到4个关键位置,并用变量pre,start,end,next标记。

3.将要反转部分截断后进行反转。

4.将截下来的部分再缝到原始链表上,调整指针指向。

5.最后调整几个变量的位置,为下一组反转做准备。

public ListNode reverseKGroup(ListNode head,int k){
    ListNode dummy = new ListNode(0);
    dummy.next = head;
    
    ListNode pre = dummy;
    ListNode end = dummy;
    while(end.next != null){
        for(int i = 0;i < k && end != null;i++){
            end = end.next;
        }
        if(end == null){
            break;
        }
        ListNode start = pre.next;
        ListNode next = end.next;
        end.next = null;
        pre.next = reverse(start);
        start.next = next;
        pre = start;
        end = pre;
    }
    return dummy.next;
}
private ListNode reverse(ListNode head){
    ListNode pre = null;
	ListNode cur = head;
	while(cur != null){
        ListNode next = cur.next;
        cur.next = pre;
        pre = cur;
        cur = next;
    }
	return pre;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值