题解 | #链表中的节点每k个一组翻转#

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

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 
# @param k int整型 
# @return ListNode类
#
class Solution:
    def reverseKGroup(self , head: ListNode, k: int) -> ListNode:
        # write code here
        stack = []
        First = True
        this = head
        count = 1
        while this is not None:
            realnext = this.next
            stack.append(this)

            if count %k==0:
                if First:
                    thisadd = stack.pop()
                    head = thisadd
                    First = False
                while len(stack)>0:
                    thisadd.next = stack.pop()
                    thisadd = thisadd.next
                stack.clear()
                thisadd.next = realnext
                
            this = realnext
            count+=1

        return head

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务