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
  • 相关阅读:
    微信小程序之遮罩功能实现
    微信小程序之获取点击软键盘搜索按钮(confirm-type="search")之后的值
    python之路——闭包函数
    python之路——装饰器函数
    Python中的单例模式的几种实现方式及优化
    08-函数
    14-定时器
    13-JS中的面向对象
    12-关于DOM操作的相关案例
    17-案例
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12821153.html
Copyright © 2011-2022 走看看