[LeetCode][python3]0025. Reverse Nodes in k-Group

class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
if not head or k<2:
return head
seq=[0]
p1=head
index=1
while p1!=None:
seq.append(p1)
p1=p1.next
if index%k==0 and index!=0:
#print("swap",index-k+1,index+1)
seq[index-k+1:index+1]=seq[index:index-k:-1]
index+=1

h=p1=ListNode(0)
for i in seq[1:]:
p1.next=i
p1=p1.next
#print(i.val)
p1.next=None
return h.next
N2I -2020.03.19
print("example of s[a:b:-1]")
s=[0,1,2,3,4,5]
print(s[1:4])
#>>[1,2,3]
print(s[3:0:-1])
#>>[3,2,1]
print(s[3:0:-2])
#>>[3,1]
print(s[0:4])
#>>[0,1,2,3]
print(s[3::-1])
#>>[3,2,1,0]
print(s[4:-1:-1]) #but -1 still represent len(s) here
#>>[]

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ruka

Ruka

HI I’m Ruka. Now a SWE in Taiwan. Contact via email: nayzi9999@gmail.com