File tree Expand file tree Collapse file tree 2 files changed +55
-1
lines changed
Expand file tree Collapse file tree 2 files changed +55
-1
lines changed Original file line number Diff line number Diff line change 3939#### 23. [ Merge k Sorted Lists] [ 47 ] : [ Solution] [ 48 ]
4040** tips: [ 分治法] [ 49 ] [ 归并排序] [ 50 ] **
4141#### 24. [ Swap Nodes in Pairs] [ 51 ] : [ Solution] [ 52 ]
42+ #### 25. [ Reverse Nodes in k-Group] [ 53 ] : [ Solution] [ 54 ]
4243
4344[ 1 ] : https://leetcode.com/problems/two-sum/
4445[ 2 ] : https://github.com/bluedazzle/leetcode_python/blob/master/src/two_sum.py
9192[ 49 ] : https://zh.wikipedia.org/wiki/%E5%88%86%E6%B2%BB%E6%B3%95
9293[ 50 ] : https://zh.wikipedia.org/wiki/%E5%BD%92%E5%B9%B6%E6%8E%92%E5%BA%8F
9394[ 51 ] : https://leetcode.com/problems/swap-nodes-in-pairs/
94- [ 52 ] : https://github.com/bluedazzle/leetcode_python/blob/master/src/swap_nodes_in_pairs.py
95+ [ 52 ] : https://github.com/bluedazzle/leetcode_python/blob/master/src/swap_nodes_in_pairs.py
96+ [ 53 ] : https://leetcode.com/problems/reverse-nodes-in-k-group/
97+ [ 54 ] : https://github.com/bluedazzle/leetcode_python/blob/master/src/reverse_nodes_in_k-group.py
Original file line number Diff line number Diff line change 1+ # Definition for singly-linked list.
2+ class ListNode (object ):
3+ def __init__ (self , x ):
4+ self .val = x
5+ self .next = None
6+
7+
8+ class Solution (object ):
9+ def reverseKGroup (self , head , k ):
10+ """
11+ :type head: ListNode
12+ :type k: int
13+ :rtype: ListNode
14+ """
15+ # head = self.convert_to_list(head)
16+ res = self .main (head , k )
17+ print res
18+ return self .convert_to_link (res )
19+
20+ def main (self , head , k , res = []):
21+ lh = len (head )
22+ if lh < k :
23+ res .extend (head )
24+ return res
25+ for i in xrange (k // 2 ):
26+ head [i ], head [k - i - 1 ] = head [k - i - 1 ], head [i ]
27+ res .extend (head [:k ])
28+ if lh > k :
29+ self .main (head [k :], k , res )
30+ return res
31+
32+ def convert_to_list (self , head ):
33+ res = []
34+ while head :
35+ res .append (head .val )
36+ head = head .next
37+ return res
38+
39+ def convert_to_link (self , res ):
40+ lh = head = ListNode (- 1 )
41+ for itm in res :
42+ head .next = ListNode (itm )
43+ head = head .next
44+ return lh .next
45+
46+
47+ h = Solution ().reverseKGroup ([1 ,2 ], 2 )
48+
49+ while h :
50+ print h .val
51+ h = h .next
You can’t perform that action at this time.
0 commit comments