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

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

    示例 1:

    输入: 1->2
    输出: false

    示例 2:

    输入: 1->2->2->1
    输出: true
    # 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:
            """要完成回文链表,首先第一步找到中间点(采取快慢指针查找)
            第二步,将查找的中间点后的链表反转
            第三步,对比两个链表的值"""
            #快慢指针
            slow,fast = head,head
            #回文最起码的条件
            if not head or not head.next:
                return True
            #找到中间点
            while fast.next and fast.next.next:
                slow,fast = slow.next,fast.next.next
            cur = slow.next #另一半链表头起点
            last = None
            #反转链表
            while cur:
                before = cur.next #防止next断裂
                cur.next = last
                last = cur
                cur = before
            #对比两个链表的值
            while last:
                if last.val != head.val:
                    return False
                last,head = last.next,head.next
            return True
  • 相关阅读:
    sdnu 1513 字符串翻转
    hdu-1559 最大子矩阵(二维树状数组模板题)
    hdu-1556 树状数组
    1049.饭盒
    1092.校门外的树
    1012.区间合并
    1054.数独
    1175.开心的金明 01背包
    空格(Space)的ASCII码值是:32
    js为lable和div赋值
  • 原文地址:https://www.cnblogs.com/lishuntao/p/12838120.html
Copyright © 2011-2022 走看看