Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
链表操作~先找到链表的中点,把链表切割成两段,然后反转后一段,接下来就是把两段链表合并起来,注意题目是要求in-place的~时间复杂度为O(n)
class Solution:~
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if head is None or head.next is None: return head
slow, fast = head, head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
head1, head2 = head, slow.next
slow.next = None
head2 = self.reverse(head2)
while head2:
tmp = head1.next
head1.next = head2
head2 = head2.next
head1.next.next = tmp
head1 = head1.next.next
def reverse(self, head):
if head is None or head.next is None:
return head
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur.next: #made a mistake here, wrote while cur instead of while cur.next. Be careful
tmp = cur.next
pre.next = tmp
cur.next = tmp.next
tmp.next = head
head = tmp
return dummy.next
链表的反转部分还有其它的写法~在链表操作题中很容易遇到~
def reverse(self, head):
pre, cur = None, head
while cur:
tmp = cur.next
cur.next= pre
pre = cur
cur = tmp
return pre
链表反转还有一种递归写法~试了一下,在这里用递归的反转链表,总是TLE