leetcode刷题python之k个一组翻转链表

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:        
        turnhead=head
        pointer=0
        while turnhead and (pointer!=k):
            turnhead=turnhead.next
            pointer+=1
        if pointer==k:
            turnhead=self.reverseKGroup(turnhead,k)
            #函数前面需要加self,赋值与返回值的类型需要一致
            while pointer:
                temp=head.next             
                head.next=turnhead               
                turnhead=head
                head=temp               
                pointer-=1           
            head=turnhead            
        return head
            

递归的思路有点费时间啊,着重记一下它的写法,

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        if not head:
            return []
        stack=[]
        result=ListNode(0)
        turnhead=result
        while True:
            pointer=k
            temp=head
            while pointer and temp:
                stack.append(temp)
                temp = temp.next
                pointer -= 1            
           
            if pointer!=0:
                turnhead.next=head
                break
                
            else:
                while stack:
                    turnhead.next=stack.pop()
                    
                    turnhead=turnhead.next
                    pointer+=1    
            head=temp    
            
        return result.next

写了个关于栈的方法,再其实的判断方面应该再完善一点,卡了半天,学会了debug哈哈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值