给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reorder-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
首先把链表从中间一分为二,用快慢指针找中点,
然后把后半段链表翻转,再依次塞进前半段链表的节点之间。
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: None Do not return anything, modify head in-place instead.
"""
if not head or not head.next:
return head
slow, fast = head, head
while fast and fast.next: #快慢指针找中点
slow = slow.next
fast = fast.next.next
l1, l2 = head, self.reverseList(slow.next) #把后半段链表翻转
slow.next = None #前半段的末尾记得置空
# self.printList(l1)
# self.printList(l2)
while l1 and l2:
cur = l2 #每次把后半段链表的第一个拿出来
l2 = l2.next
cur.next = l1.next #插到前半段链表里
l1.next = cur
l1 = l1.next.next
return head
def reverseList(self, head):
if not head or not head.next:
return head
p = self.reverseList(head.next)
head.next.next = head
head.next = None
return p
def printList(self, head):
l = []
p = head
while p:
l.append(p.val)
p = p.next
print l