zoukankan      html  css  js  c++  java
  • 【leetcode】143. Reorder List

    题目如下:

    Given a singly linked list LL0→L1→…→Ln-1→Ln,
    reorder it to: L0→LnL1→Ln-1→L2→Ln-2→…

    You may not modify the values in the list's nodes, only nodes itself may be changed.

    Example 1:

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

    Example 2:

    Given 1->2->3->4->5, reorder it to 1->5->2->4->3.

    解题思路:我的方法是用一个list保存链表后半部分的节点,接下来从头开始遍历链表,把list中的第一个节点插入到原链表的第一个节点后,第二个插入到原链表的第二个节点后面,直到list全部节点都插入到原链表为止。

    代码如下:

    # 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: None Do not return anything, modify head in-place instead.
            """
            if head == None:
                return
            mid,tail = head,head
            while tail != None:
                tail = tail.next
                if tail == None:
                    break
                tail = tail.next
                if tail == None:
                    break
                mid = mid.next
            l = []
            second_half = mid.next
            mid.next = None
            while second_half != None:
                l.insert(0,second_half)
                second_half = second_half.next
    
            current = head
            while len(l) > 0:
                node = l.pop(0)
                node.next = current.next
                current.next = node
                current = current.next.next
  • 相关阅读:
    序列化 Serialization
    http soap关系
    sql 查询
    返回最后插入到标识列的值(scope_identity.ident_current.@@identity)
    匿名方法
    九、volatile与Java内存模型
    八、Java内存模型JMM
    十、CAS
    CUSTOM ROUTE CONSTRAINTS
    获取本地数据库
  • 原文地址:https://www.cnblogs.com/seyjs/p/10559919.html
Copyright © 2011-2022 走看看