Source of the topic:
https://leetcode.com/problems/reverse-nodes-in-k-group/
Test Instructions Analysis:
This is similar to the previous topic, enter a list and an integer k. Flip it every k. You cannot change the value of a linked list.
Topic Ideas:
To make this topic more intuitive, write a function that flips the list. The next step is the list operation.
Code (Python):
1 #Definition for singly-linked list.2 #class ListNode (object):3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 classsolution (object):7 defreverse (self,start,end):8Nhead =listnode (0)9Nhead.next =StartTen whileNhead.next! =End: OneTMP =Start.next AStart.next =Tmp.next -Tmp.next =Nhead.next -Nhead.next =tmp the return[End,start] - defReversekgroup (self, head, K): - """ - : Type Head:listnode + : Type K:int - : Rtype:listnode + """ AAns =listnode (0) at ifHead = =None: - returnNone -Ans.next =Head -Start =ans - whileStart.next! =None: -End =Start ini =0 - whileI < K-1: toEnd =End.next + ifEnd.next = =None: - returnAns.next thei + = 1 *TMP =self.reverse (Start.next,end.next) $Start.next =Tmp[0]Panax NotoginsengStart = Tmp[1] - returnAns.next
View Code
Reprint Please specify source: http://www.cnblogs.com/chruny/p/4872990.html
[Leetcode] (python): 025-reverse Nodes in K-group