# 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哈哈