LeetCode 25. K 个一组翻转链表(Java版)

题目

25. K 个一组翻转链表

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
在这里插入图片描述

题解

我的指针的做法

我是喜欢用迭代来进行翻转的所以我这里还是用了迭代的思想。
先找到需要反转的链表,然后翻转,然后在进行拼接。看起来很简单,我们我们先遍历需要反转的链表段子,也就是先走过k个ListNode。然后用几个变量先记录下当前的链表的情况。
reverse(start,end) 表示翻转start到end的链表,并且返回反转后的头结点。
在这里插入图片描述
在这里插入图片描述

public ListNode reverseKGroup(ListNode head, int k) {
	if (head == null || head.next == null) {
		return head;
	}
	ListNode dummy= new ListNode(0);
	ListNode pre = dummy;
	ListNode cur = head;
	pre.next = cur;
	ListNode start = null;
	ListNode end = null;
	ListNode after = null;
	while (cur != null) {
		boolean isEnd = false;
		start = cur;
		for (int i = 0; i < k-1; i++) {
			if (cur == null) {
				isEnd = true;
				break;
			}
			cur = cur.next;
		}
		if (isEnd || cur == null) {
			break;
		}
		end = cur;
		after = cur.next;
		pre.next = reserve(start, end);
		start.next = after;
		pre = start;
		cur = after;
	}
	return dummy.next;
}

// 反转链表
private ListNode reserve(ListNode start, ListNode end) {
	ListNode pre = null;
	ListNode current = start;
	ListNode after = null;
	while (pre != end && current != null) {
		after = current.next;
		current.next = pre;
		pre = current;
		current = after;
	}
	return end;
}

用栈的思想就很简单了,但是应该是不符合的题目的不能用额外的空间这个条件

public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null || head.next == null) {
        return head;
    }
    Stack<ListNode> stack = new Stack<>();
    boolean isFirst = true;
    ListNode dummyNode = new ListNode(0);
    ListNode pre = dummyNode;
    while (true) {
        int count = 0;
        ListNode temp = head;
        // 开始填栈,要么到了尾结点,要么栈的元素的数量等于k
        while (temp != null && count < k) {
            stack.push(temp);
            temp = temp.next;
            count++;
        }
        // 到了尾结点了。
        if (count < k) {
            pre.next = head;
            break;
        }
        // 根据栈里的元素进行反转
        while (!stack.isEmpty()) {
            pre.next = stack.pop();
            pre = pre.next;
        }
        // 为了防止下一个没满足反转的条件,直接退出的情况
        pre.next = temp;
        head = temp;
    }
    return dummyNode.next;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值