zoukankan      html  css  js  c++  java
  • 143. 重排链表

    给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
    将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…

    你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    示例 1:

    给定链表 1->2->3->4, 重新排列为 1->4->2->3.
    示例 2:

    给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/reorder-list
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, val=0, next=None):
    #         self.val = val
    #         self.next = next
    class Solution:
        def reorderList(self, head: ListNode) -> None:
            """
            Do not return anything, modify head in-place instead.
            """
            if not head:return
            cur=head
            nodes=[]
            while cur:
                nodes.append(cur)
                cur=cur.next
            l=0
            r=len(nodes)-1
            while l<r:
                nodes[l].next=nodes[r]
                l+=1
                nodes[r].next=nodes[l]
                r-=1
            nodes[l].next=None
  • 相关阅读:
    【项目】项目1
    Python脚本1
    Python基础24
    Python基础23(习惯)
    01-Spring(1)
    12-Shell(2)
    11-Shell(1)
    10-搭建EE环境
    09-常用指令(3)
    08-常用指令(2)
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13844363.html
Copyright © 2011-2022 走看看