[leetcode]题解(python):025-凯发k8官方网
凯发k8官方网
收集整理的这篇文章主要介绍了
[leetcode]题解(python):025-reverse nodes in k-group
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
题目来源:
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
转载于:https://www.cnblogs.com/chruny/p/4872990.html
与50位技术专家面对面20年技术见证,附赠技术全景图总结
以上是凯发k8官方网为你收集整理的[leetcode]题解(python):025-reverse nodes in k-group的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 前端开发必备!emmet使用手册
- 下一篇: [bzoj3874/ahoi2014]宅