zoukankan      html  css  js  c++  java
  • Leetcode刷题日记-剑指Offer(2020.6.19):从尾到头打印链表

    题目描述如下:

     思路描述:

    这是一道简单的链表题目,我开始用了头插法,但是时间开销过大,因此进行了优化,分为以下几种方法给大家讲解

    方法一:使用头插法,我们可以直接使用列表的插入方法,每次插入数据,只插入在首位

    代码如下:

     1 # -*- coding: utf-8 -*-
     2 """
     3 @time: 2020/6/19 9:14
     4 @author: ZFJ
     5 @contact: 1094038955@qq.com
     6 @software: PyCharm
     7 @file: 从尾到头打印链表.py
     8 """
     9 
    10 
    11 # Definition for singly-linked list.
    12 # class ListNode(object):
    13 #     def __init__(self, x):
    14 #         self.val = x
    15 #         self.next = None
    16 
    17 class Solution(object):
    18     def reversePrint(self, head):
    19         """
    20         :type head: ListNode
    21         :rtype: List[int]
    22         """
    23         result = []
    24         while head:
    25             result.insert(0, head.val)
    26             head = head.next
    27         return result

    方法二:通常,这种情况下,我们不希望修改原链表的结构。返回一个反序的链表,这就是经典的“后进先出”,我们可以使用栈实现这种顺序。每经过一个结点的时候,把该结点放到一个栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,给一个新的链表结构,这样链表就实现了反转。

     1 class Solution(object):
     2     def reversePrint(self, head):
     3         """
     4         :type head: ListNode
     5         :rtype: List[int]
     6         """
     7         stack = []
     8         # 当链表不为空时,我们就入栈
     9         while head:
    10             stack.append(head.val)
    11             head = head.next
    12         # 存储出栈的结果
    13         result = []
    14         # 当栈不为空
    15         while stack:
    16             result.append(stack.pop())
    17         return result
  • 相关阅读:
    (3)C++复合类型
    (2)C++基本类型
    (7)js调试
    Oracle语句优先级
    oracle排序问题
    jsp四大对象
    postgresql时间加减计算
    全角空格,跟汉字一样宽
    bzoj1433 [ZJOI2009]假期的宿舍 最大流
    BZOJ 1264 AHOI2006 基因匹配Match 动态规划+树状数组
  • 原文地址:https://www.cnblogs.com/ZFJ1094038955/p/13162800.html
Copyright © 2011-2022 走看看