zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):链表类:第143题:重排链表:给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

    题目:
    重排链表:给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…  你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。 
    思路:
    使用了懒人做法,使用了栈,应该还有更好的方法,想到后做补充。
    程序:
    # 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 None
            myStack = []
            index1 = head
            counter = 0
            while index1:
                myStack.append(index1)
                index1 = index1.next
                counter += 1
            num_rotate = counter // 2
            index2 = head
            while num_rotate:
                tmp_node = myStack.pop()
                tmp_node.next = index2.next
                index2.next = tmp_node
                index2 = tmp_node.next
                num_rotate -= 1
            index2.next = None
  • 相关阅读:
    Spring AOP切点表达式用法总结
    各种文档地址记录
    回顾乐信集团工作经历
    Redux的简单使用
    简单介绍软件测试(一)
    jupyter notebook 安装代码提示功能
    解决matplotlib不显示中文的问题
    前端生成二维码并下载(PC端)
    XSS绕过常见方式
    JWT的安全问题
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12821153.html
Copyright © 2011-2022 走看看