zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):链表类:第234题:回文链表:请判断一个链表是否为回文链表。

    题目:
    回文链表:请判断一个链表是否为回文链表。
    进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
    思路:
    利用栈的性质来判断很方便,但是空间复杂度为O(n)。
    想一想空间复杂度为O(1) 的方法,之后补充。 
    程序1:
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    class Solution:
        def isPalindrome(self, head: ListNode) -> bool:
            if not head:
                return True
            mystack = []
            index1 = head
            while index1:
                mystack.append(index1)
                index1 = index1.next
            index2 = head
            while mystack:
                index3 = mystack.pop()
                if index2.val == index3.val:
                    index2 = index2.next
                elif index2.val != index3.val:
                    return False
            return True
  • 相关阅读:
    数据库子查询
    数据库简介
    MySql数据类型
    Jquery与js简单对比
    JS-对象
    JS-DOM
    JS-数组
    JS-函数
    JS-json
    JS-类型相关
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12813888.html
Copyright © 2011-2022 走看看