BM3 链表中的节点每 k 个一组翻转

在这里插入图片描述
第一种解题思路:

  1. 循环链表,每次循环将链表的结点存进栈
  2. 判断栈的长度,是否等于 K ,等于 K,则循环出栈
  3. 循环链表后,判断栈是否为空,不为空则循环出栈
  4. 然后插入新链表的尾部
  5. 最后返回新链表
    时间复杂度为O(n),空间复杂度为O(n),不合题意。
import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || head.next == null || k == 1) {
            return head;
        }

        Stack<ListNode> stack = new Stack<>();
        ListNode cur = new ListNode(-1);
        ListNode pre = cur;
        ListNode node = null;

        while (head != null) {
            stack.push(head);
            head = head.next;
            if (stack.size() == k) {
                while (!stack.isEmpty()) {
                    node = stack.pop();
                    node.next = null;
                    cur.next = node;
                    cur = cur.next;
                }
            }
        }

        while (!stack.isEmpty()) {
            node = stack.pop();
            //一个个结点往cur后面插
            node.next = cur.next;
            cur.next = node;
        }

        return pre.next;
    }

}

第二种方法:指针前移,分批往前移思想,参考牛客大佬"不上蓝到绿不改名"
在这里插入图片描述

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 * }
 */

public class Solution {
    /**
      *
      * @param head ListNode类
      * @param k int整型
      * @return ListNode类
      */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (head == null || k <= 1) {
            return head;
        }
        ListNode result = new ListNode(-1);
        ListNode now = result;

        int length = getLength(head);
        //循环次数
        int size = length / k;
        for (int i = 0; i < size; i++) {
            ListNode node = null;
            ListNode tmp = null;
            for (int j = 0; j < k; j++) {
                node = head.next;
                head.next = tmp;
                tmp = head;
                head = node;
            }
            now.next = tmp;
            while (now.next != null) {
                now = now.next;
            }
        }
        now.next = head;
        return result.next;
    }

    //计算链表的长度
    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值