https://leetcode.com/problems/reorder-list/
code 1
参考http://bookshadow.com/weblog/2015/01/29/leetcode-reorder-list/
思路:
1. 利用快慢指针找到链表中点mid,将链表分为左右两半
2. 将链表的右半部分就地逆置
3. 合并链表的左右两部分(一左一右的穿过所有元素)
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head and head.next and head.next.next:
#find mid
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
mid = slow
#cut in the mid
left = head
right = mid.next
if right is None:
return head
mid.next = None
#reverse right half
cursor = right.next
right.next = None
while cursor:
next = cursor.next
cursor.next = right
right = cursor
cursor = next
#merge left and right
dummy = ListNode(0)
while left or right:
if left is not None:#注意这里的条件
dummy.next = left
left = left.next
dummy = dummy.next
if right is not None:#用dummy左右穿过所有元素
dummy.next = right
right = right.next
dummy = dummy.next
我的递归算法,TLE超时
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if not head or not head.next or not head.next.next: return head
cur = head
dummy = ListNode(0)
dummy.next = head
pre, last = dummy, head
while last.next:
pre = last
last = last.next
pre.next = None
tmp = cur.next
cur.next, last.next = last, tmp
self.reorderList(tmp)
code 2
解题思路:1,先将链表截断为两个相等长度的链表,如果链表长度为奇数,则第一条链表长度多1。如原链表为L={1,2,3,4,5},那么拆分结果为L1={1,2,3};L2={4,5}。拆分的技巧还是快慢指针的技巧。
2,将第二条链表L2翻转,如将L2={4,5}翻转为L2={5,4}。
3,按照题意归并链表。