# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reorderList(self, head):
"""
:type head: ListNode
:rtype: void Do not return anything, modify head in-place instead.
"""
if head == None or head.next == None:
return
fast = head
slow = head
while fast.next != None and fast.next.next != None:
fast = fast.next.next
slow = slow.next
head2 = slow.next
slow.next = None
head2 = self.reverse(head2)
self.merge(head, head2)
def reverse(self, node):
dummy = ListNode(0)
dummy.next = node
p = node
# dummy->..-p->curNode->cur.next..
# dummy->curNode->..->p->cur.next..
while p.next != None:
curNode = p.next
p.next = curNode.next
curNode.next = dummy.next
dummy.next = curNode
return dummy.next
def merge(self, head, head2):
p = head
head = head.next
while head and head2:
# Insert a head2 node.
p.next = head2
head2 = head2.next
p = p.next
# Insert a head node.
p.next = head
head = head.next
p = p.next
if head == None:
p.next = head2
if head2 == None:
p.next = head
https://leetcode.com/problems/reorder-list/#/description
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}
.