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
  • 相关阅读:
    Magento安装教程
    让老婆爱你的十大方法。
    easy ui layout设计
    下交叉综合症
    fileloder.js+struts2实现文件异步上传,无页面刷新效果。
    将mysql中的Blob的图片在jsp中显示
    详解CSS样式的position属性
    Struts2与Spring的整合
    Play Framework常用标签list,set,如何遍历list、map类型数据
    我所理解的团队
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12821153.html
Copyright © 2011-2022 走看看