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
  • 相关阅读:
    07.swoole学习笔记--tcp客户端
    06.swoole学习笔记--异步tcp服务器
    04.swoole学习笔记--webSocket服务器
    bzoj 4516: [Sdoi2016]生成魔咒
    bzoj 3238: [Ahoi2013]差异
    bzoj 4566: [Haoi2016]找相同字符
    bzoj 4199: [Noi2015]品酒大会
    后缀数组之hihocoder 重复旋律1-4
    二分查找
    内置函数--sorted,filter,map
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12821153.html
Copyright © 2011-2022 走看看