您的位置:首页 > 编程语言 > Python开发

【LeetCode with Python】 Reorder List

2014-07-06 15:24 417 查看
博客域名:http://www.xnerv.wang

原题页面:https://oj.leetcode.com/problems/reorder-list/

题目类型:

难度评价:★

本文地址:/article/1377501.html

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}
.

class Solution:

    # @param head, a ListNode
    # @return nothing
    def reorderList(self, head):

        if None == head:
            return
        cur = head
        count = 0
        while None != cur:
            cur = cur.next
            count += 1
        if count <= 2:
            return

        half_count = (count - 1) / 2
        cur2 = head
        for i in range(0, half_count):
            cur2= cur2.next
        cur2_next = cur2.next
        cur2.next = None
        cur2 = reverse_list(cur2_next, None, None)

        cur1 = head
        time_count = int(count / 2)
        for i in range(0, time_count):
            cur2_next = cur2.next
            cur2.next = cur1.next
            cur1.next = cur2
            cur1 = cur2.next
            cur2 = cur2_next
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: