码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode]题解(python):025-Reverse Nodes in k-Group

时间:2015-10-12 22:35:17      阅读:329      评论:0      收藏:0      [点我收藏+]

标签:

题目来源:

  https://leetcode.com/problems/reverse-nodes-in-k-group/


 

题意分析:

  这道题目和上一题目类似,输入一个链表和一个整型k。每k个翻转一下。不能更改链表的值。


 

题目思路:

  这道题目为了更加直观,先写一个翻转链表的函数。接下来就是链表操作。


 

代码(python):

技术分享
 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 class Solution(object):
 7     def reverse(self,start,end):
 8         nhead = ListNode(0)
 9         nhead.next = start
10         while nhead.next != end:
11             tmp = start.next
12             start.next = tmp.next
13             tmp.next = nhead.next
14             nhead.next = tmp
15         return [end,start]
16     def reverseKGroup(self, head, k):
17         """
18         :type head: ListNode
19         :type k: int
20         :rtype: ListNode
21         """
22         ans = ListNode(0)
23         if head == None:
24             return None
25         ans.next = head
26         start = ans
27         while start.next != None:
28             end = start
29             i = 0
30             while i < k - 1:
31                 end = end.next
32                 if end.next == None:
33                     return ans.next
34                 i += 1
35             tmp = self.reverse(start.next,end.next)
36             start.next = tmp[0]
37             start = tmp[1]
38         return ans.next
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/4872990.html

[LeetCode]题解(python):025-Reverse Nodes in k-Group

标签:

原文地址:http://www.cnblogs.com/chruny/p/4872990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!