# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return nothing
def reorderList(self, head):
if not head or not head.next: return head
#find the middle node
slow=fast=ListNode(0)
slow.next=head
n=0#length of the rear half of the linked list
while fast and fast.next:
n+=1
slow=slow.next
fast=fast.next.next
if not fast:
n=n-1
mid=slow
rear=mid.next
mid.next=None
dummy=ListNode(0)
for i in range(n):
temp=dummy.next
dummy.next=rear
rear=rear.next
dummy.next.next=temp
crt=head
insert_node=dummy.next
for i in reversed(range(n)):
temp=crt.next
crt.next=insert_node
insert_node=insert_node.next
crt.next.next=temp
crt=temp
return head
Thursday, September 18, 2014
Leetcode: Reorder List @Python
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment