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

时间:2025-01-02 20:07:08

题目来源:

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


题意分析:

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


题目思路:

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


代码(python):

 # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverse(self,start,end):
nhead = ListNode(0)
nhead.next = start
while nhead.next != end:
tmp = start.next
start.next = tmp.next
tmp.next = nhead.next
nhead.next = tmp
return [end,start]
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
ans = ListNode(0)
if head == None:
return None
ans.next = head
start = ans
while start.next != None:
end = start
i = 0
while i < k - 1:
end = end.next
if end.next == None:
return ans.next
i += 1
tmp = self.reverse(start.next,end.next)
start.next = tmp[0]
start = tmp[1]
return ans.next

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