美文网首页
143. Reorder List

143. Reorder List

作者: Leorio_c187 | 来源:发表于2017-06-15 09:40 被阅读0次

题目

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

思路

三部曲思路,很直接

  • 把list拆成前半段和后半段
  • 把后半段reverse
  • 把后半段依次插入前半段的相应位置(在148中学到的)

Python

# 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.
        """
        #3 step methods. 1.find the mid. 2.Reverse the second half. 3.insert one buy one
        if not head or not head.next: return #basecase
        
        #First step, find mid
        slow = fast = head
        while fast and fast.next:
            # pre = slow
            slow = slow.next
            fast = fast.next.next
        shalf = slow.next
        slow.next = None #make head to be the first half
        
        #reverse the second half
        r_shalf = None
        while shalf:
            temp = shalf.next
            shalf.next = r_shalf
            r_shalf = shalf
            shalf = temp
            
        #insert the second half to the first half one buy one.
        node = head
        while r_shalf:
            temp = r_shalf.next
            r_shalf.next = node.next
            node.next = r_shalf
            r_shalf = temp
            node = node.next.next
        
            
            
        
        
        
        

相关文章

  • 143. Reorder List

    题目143. Reorder List Given a singly linked list L: L0→L1→…...

  • 143. Reorder List

    实在是太困了 看不下去这一题的指针,明早上看

  • 143. Reorder List

    题目分析 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorde...

  • 143. Reorder List

    题目 Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder ...

  • 143. Reorder List

    分为以下几个步骤,1使用快慢指针找到中间节点,2翻转后半部分,3逐个插入节点。

  • 143. Reorder List

    Given a singly linked list L: L0→L1→…→Ln-1→Ln,reorder it ...

  • 143. Reorder List

    题目描述:给链表如L: L0→L1→…→Ln-1→Ln,将其重新排序为L0→Ln→L1→Ln-1→L2→Ln-2→...

  • 143. Reorder List

    这题很简单,不过很容易出bug特别在merge的时候,所以一定要逻辑清楚,先写好框架

  • 143. Reorder List

    Example 1: Given 1->2->3->4, reorder it to 1->4->2->3.Exa...

  • 143. Reorder List

    重排链表L0 → L1 → … → Ln - 1 → Ln重写为L0 → Ln → L1 → Ln - 1 → L...

网友评论

      本文标题:143. Reorder List

      本文链接:https://www.haomeiwen.com/subject/tvjyqxtx.html