栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【LeetCode】K 个一组翻转链表

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【LeetCode】K 个一组翻转链表

K 个一组翻转链表

题意

给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

k 是一个正整数,它的值小于或等于链表的长度。如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。

你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。

示例:

输入:head = [1,2,3,4,5], k = 2
输出:[2,1,4,3,5]

思路
  • 先实现两个函数,getGroupEnd 和 reverse,前一个函数根据开始起点start和间隔k,返回一组节点的尾部节点end;后一个函数实现对本组的链表的翻转,并将start的下一个节点指向end;
  • 判断链表能否凑够第一组,若凑不够,直接返回head;若第一组凑齐了,则对第一组执行reverse操作,然而定义改组节点翻转完成后的尾部节点 lastEnd = start,若lastEnd不为空,循环执行后续每组链表。
代码

Python

class ReverseKGroup:
    """
    K 个一组翻转链表
    """
    def solution(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        def getKGroupEnd(s, k):
            k -= 1
            while k != 0 and s:
                s = s.next
                k -= 1
            return s

        def reverse(start, end):
            end = end.next
            pre, next = None, None
            cur = start
            while cur != end:
                next = cur.next
                cur.next = pre
                pre = cur
                cur = next

            start.next = end

        start = head
        end = getKGroupEnd(start, k)
        # 凑不够一组,直接返回head
        if not end:
            return head

        # 第一组凑齐了,最终返回的head指向第一组的尾节点
        head = end
        reverse(start, end)

        # 上一组的结尾节点
        lastEnd = start
        while lastEnd.next:
            start = lastEnd.next
            end = getKGroupEnd(start, k)
            if not end:
                return head
            reverse(start, end)
            lastEnd.next = end
            # 这一组的结尾节点
            lastEnd = start

        return head


Java

public class ReverseNodesInKGroup {

	// 不要提交这个类
	public static class ListNode {
		public int val;
		public ListNode next;
	}

	public static ListNode reverseKGroup(ListNode head, int k) {
		ListNode start = head;
		ListNode end = getKGroupEnd(start, k);
		if (end == null) {
			return head;
		}
		// 第一组凑齐了!
		head = end;
		reverse(start, end);
		// 上一组的结尾节点
		ListNode lastEnd = start;
		while (lastEnd.next != null) {
			start = lastEnd.next;
			end = getKGroupEnd(start, k);
			if (end == null) {
				return head;
			}
			reverse(start, end);
			lastEnd.next = end;
			lastEnd = start;
		}
		return head;
	}

	public static ListNode getKGroupEnd(ListNode start, int k) {
		while (--k != 0 && start != null) {
			start = start.next;
		}
		return start;
	}
	public static void reverse(ListNode start, ListNode end) {
		end = end.next;
		ListNode pre = null;
		ListNode cur = start;
		ListNode next = null;
		while (cur != end) {
			next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		start.next = end;
	}
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/857834.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号