自学内容网 自学内容网

leetcode25. 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.
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]
给你链表的头节点 head ,每 k 个节点一组进行翻转,请你返回修改后的链表。

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

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

class Solution:
    def reverseKGroup(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        h = t = ListNode(0, head)
        p, stack = head, []        
        while True:
            for _ in range(k):
                if p: 
                    stack.append(p)     # 压栈
                    p = p.next
                else: return h.next     # 不满栈,直接返回
            for _ in range(k):
                t.next = stack.pop()    # 出栈,同时续到链表尾部
                t = t.next
            t.next = p                  # 连接后段链表

原文地址:https://blog.csdn.net/weixin_44245188/article/details/143662356

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!