本文主要是介绍Python | Leetcode Python题解之第143题重排链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
题解:
class Solution:def reorderList(self, head: ListNode) -> None:if not head:returnmid = self.middleNode(head)l1 = headl2 = mid.nextmid.next = Nonel2 = self.reverseList(l2)self.mergeList(l1, l2)def middleNode(self, head: ListNode) -> ListNode:slow = fast = headwhile fast.next and fast.next.next:slow = slow.nextfast = fast.next.nextreturn slowdef reverseList(self, head: ListNode) -> ListNode:prev = Nonecurr = headwhile curr:nextTemp = curr.nextcurr.next = prevprev = currcurr = nextTempreturn prevdef mergeList(self, l1: ListNode, l2: ListNode):while l1 and l2:l1_tmp = l1.nextl2_tmp = l2.nextl1.next = l2l1 = l1_tmpl2.next = l1l2 = l2_tmp
这篇关于Python | Leetcode Python题解之第143题重排链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!