zoukankan      html  css  js  c++  java
  • 回文链表

    请判断一个链表是否为回文链表。

    示例 1:
    
    输入: 1->2
    输出: false
    示例 2:
    
    输入: 1->2->2->1
    输出: true
    进阶:
    你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?

    代码思路:

    不考虑空间复杂度的话,这道题其实很容易。但是一旦考虑了空间复杂度,就表示需要对原始链表进行操作。

    首先先利用快慢指针找到原始链表的中间,因为考虑到奇偶,所以slow指针需要往后走一位,保证需要反转的链表是跳过了奇数的中间位,然后再反转后面的链表。这个时候只要保证判断的后面链表不为空就可以了,前面的链表我不管。而且快指针有没有走到头我也不用管,反正一旦不能走了我慢指针一定是在中间的前一位。

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def isPalindrome(self, head):
            """
            :type head: ListNode
            :rtype: bool
            """
    
            if not head or not head.next:
                return True
            slow=fast=head
            while fast.next and fast.next.next:
                
                slow=slow.next
                fast=fast.next.next
                
            
            slow=self.reverseList(slow.next)
            
            while slow:
                if head.val != slow.val:
                    return False
                slow=slow.next
                head=head.next
            return True
        
        
        def reverseList(self, head):
            new_head = None
            while head:
                p = head
                head = head.next
                p.next = new_head
                new_head = p
            return new_head
            
  • 相关阅读:
    如何简化你的Vuex Store
    深入理解React中的setState
    vue双向绑定原理分析
    vue递归组件:树形控件
    Vue 3.0 的 Composition API 尝鲜
    React Native 与 Flutter 的跨平台之争
    javascript 变量赋值和 参数传递
    setTimeout 和 throttle 那些事儿
    一道面试题-变量声明提升~
    匹配文件扩展名两种方式
  • 原文地址:https://www.cnblogs.com/guangluwutu/p/10697400.html
Copyright © 2011-2022 走看看