【LeetCode with Python】 Reorder List

来源:互联网 发布:游戏程序员的职业诉求 编辑:程序博客网 时间:2024/06/07 01:32
博客域名:http://www.xnerv.wang
原题页面:https://oj.leetcode.com/problems/reorder-list/
题目类型:
难度评价:★
本文地址:http://blog.csdn.net/nerv3x3/article/details/37337343

Given a singly linked list L: L0L1→…→Ln-1Ln,
reorder it to: L0LnL1Ln-1L2Ln-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

0 0
原创粉丝点击