25.leetcode题目讲解(Python):k个一组翻转链表
2018-10-16 本文已影响68人
夏山闻汐
题目如下:
题目这道题我的解法效率不是特别高,抛砖引玉,代码如下,我会找时间重新再写另外一个解法:
class Solution:
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if head is None or head.next is None or k == 1:
return head
temp = []
reverse_list = []
while head is not None:
temp.append(head.val)
head = head.next
if k == len(temp):
temp.reverse()
cur = ListNode(temp[0])
head = cur
cur = ListNode(temp[1])
head.next = cur
for j in range(2, len(temp)):
cur.next = ListNode(temp[j])
cur = cur.next
return head
i = 0
while i + k <= len(temp):
re_temp = temp[i:i + k]
re_temp.reverse()
for t in re_temp:
reverse_list.append(t)
i = i + k
for t in temp[i:]:
reverse_list.append(t)
cur = ListNode(reverse_list[0])
head = cur
cur = ListNode(reverse_list[1])
head.next = cur
for j in range(2, len(reverse_list)):
cur.next = ListNode(reverse_list[j])
cur = cur.next
return head
其它题目:leetcode题目答案讲解汇总(Python版 持续更新)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)