题目来源:
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
转载请注明出处:http://www.cnblogs.com/chruny/p/4872990.html