leetcode-回文链表

234. 回文链表

在此对比的值,不是节点

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        dummy_head = ListNode(next=head)
        cur = dummy_head.next
        val = []
        while cur:
            val.append(cur.val)
            cur = cur.next
        return val==val[::-1]

使用快慢指针法找到链表的中点,将后半部分链表反转,最后比较前半部分和反转后的后半部分是否相同。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: Optional[ListNode]) -> bool:
        if not head or not head.next:
            return True
        dummy_head = ListNode(next=head)
        slow, fast = dummy_head, dummy_head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        prev, cur = None, slow.next
        while cur:
            tmp = cur.next
            cur.next = prev
            prev = cur
            cur = tmp
        p1, p2 = dummy_head.next, prev
        while p2:
            if p1.val != p2.val:
                return False
            p1 = p1.next
            p2 = p2.next
        return True

相关推荐

  1. leetcode-

    2024-02-05 18:32:01       64 阅读
  2. leetcode 234

    2024-02-05 18:32:01       48 阅读
  3. LeetCode-热题100:234.

    2024-02-05 18:32:01       37 阅读
  4. Leetcode234.判断是否是

    2024-02-05 18:32:01       22 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-05 18:32:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-05 18:32:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-02-05 18:32:01       82 阅读
  4. Python语言-面向对象

    2024-02-05 18:32:01       91 阅读

热门阅读

  1. c# File.WriteAllLines 和 File.WriteAllText

    2024-02-05 18:32:01       52 阅读
  2. 学习的数据结构和算法第2天

    2024-02-05 18:32:01       53 阅读
  3. 【Firebase】Could not find firebase-encoders-json-18.0.1.aar

    2024-02-05 18:32:01       49 阅读
  4. 常见的几种算法排序(C#)

    2024-02-05 18:32:01       56 阅读
  5. nacos集群搭建

    2024-02-05 18:32:01       50 阅读
  6. 【数据结构与算法】暴力匹配子串-C语言版

    2024-02-05 18:32:01       53 阅读
  7. Linux常见面试题汇总

    2024-02-05 18:32:01       52 阅读
  8. easyexcel解析跨多行的数据

    2024-02-05 18:32:01       54 阅读