[leetcode]Reorder List @ Python


原題地址:http://oj.leetcode.com/problems/reorder-list/

題意:

Given a singly linked list LL0L1→…→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}.

解題思路:1,先將鏈表截斷為兩個相等長度的鏈表,如果鏈表長度為奇數,則第一條鏈表長度多1。如原鏈表為L={1,2,3,4,5},那么拆分結果為L1={1,2,3};L2={4,5}。拆分的技巧還是快慢指針的技巧。

       2,將第二條鏈表L2翻轉,如將L2={4,5}翻轉為L2={5,4}。

              3,按照題意歸並鏈表。

# 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 head==None or head.next==None or head.next.next==None: return head
        
        # break linked list into two equal length
        slow = fast = head                              #快慢指針技巧
        while fast and fast.next:                       #需要熟練掌握
            slow = slow.next                            #鏈表操作中常用
            fast = fast.next.next
        head1 = head
        head2 = slow.next
        slow.next = None

        # reverse linked list head2
        dummy=ListNode(0); dummy.next=head2             #翻轉前加一個頭結點
        p=head2.next; head2.next=None                   #將p指向的節點一個一個插入到dummy后面
        while p:                                        #就完成了鏈表的翻轉
            tmp=p; p=p.next                             #運行時注意去掉中文注釋
            tmp.next=dummy.next
            dummy.next=tmp
        head2=dummy.next

        # merge two linked list head1 and head2
        p1 = head1; p2 = head2
        while p2:
            tmp1 = p1.next; tmp2 = p2.next
            p1.next = p2; p2.next = tmp1
            p1 = tmp1; p2 = tmp2

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM