回文链表(Leetcode)

题目

给你一个单链表的头节点 ,请你判断该链表是否为

回文链表。如果是,返回 ;否则,返回

解题

python 复制代码
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


def isPalindrome(head: ListNode) -> bool:
    if not head or not head.next:
        return True

    # 快慢指针找到链表中点
    slow, fast = head, head
    while fast and fast.next:
        slow = slow.next
        fast = fast.next.next

    # 反转链表后半部分
    prev = None
    while slow:
        temp = slow.next
        slow.next = prev
        prev = slow
        slow = temp

    # 比较前半部分和反转后的后半部分
    left, right = head, prev
    while right:
        if left.val != right.val:
            return False
        left = left.next
        right = right.next

    return True


def print_linked_list(head):
    while head:
        print(head.val, end=" -> ")
        head = head.next
    print("None")


def create_linked_list(arr):
    if not arr:
        return None
    head = ListNode(arr[0])
    current = head
    for val in arr[1:]:
        current.next = ListNode(val)
        current = current.next
    return head


# 测试用例
def test_isPalindrome():
    test_cases = [
        [1, 2, 2, 1],
        [1, 2, 3, 2, 1],
        [1, 2, 3, 4, 5],
        [1, 2],
        [1],
        []
    ]

    for i, values in enumerate(test_cases):
        head = create_linked_list(values)
        print(f"Test case {i + 1}:", )
        print_linked_list(head)
        result = isPalindrome(head)
        print(f"Result: {result}\n")


# 运行测试
test_isPalindrome()

Test case 1:

1 -> 2 -> 2 -> 1 -> None

Result: True

Test case 2:

1 -> 2 -> 3 -> 2 -> 1 -> None

Result: True

Test case 3:

1 -> 2 -> 3 -> 4 -> 5 -> None

Result: False

Test case 4:

1 -> 2 -> None

Result: False

Test case 5:

1 -> None

Result: True

Test case 6:

None

Result: True

相关推荐
Lucky_ldy8 小时前
数据结构从入门到精通:顺序表
数据结构·链表
金牌归来发现妻女流落街头8 小时前
【LeetCode 第207题】
算法·leetcode·拓扑·领接表
熬夜敲代码的猫8 小时前
AVL树(C++详解版)
数据结构·c++·算法
并不喜欢吃鱼9 小时前
从零开始 C++-----十一【C++ 数据结构】红黑树全解析:从定义到工程实现(一文搞定,十分详细)
开发语言·数据结构·c++
星恒随风9 小时前
C语言数据结构排序算法详解(上):从插入排序、希尔排序到选择排序、堆排序
c语言·数据结构·笔记·学习·排序算法
迈巴赫车主9 小时前
蓝桥杯21247弹跳鞋java
java·开发语言·数据结构·算法·职场和发展·蓝桥杯
alphaTao9 小时前
LeetCode 每日一题 2026/5/25-2026/5/31
算法·leetcode
菜菜的顾清寒9 小时前
力扣HOT100(41)动态规划-杨辉三角
算法·leetcode·动态规划
Cthy_hy9 小时前
Python算法竞赛:集合去重+字典映射 核心用法一站式整理
数据结构·python·算法
happymaker062610 小时前
LeetCodeHot100——盛水最多的容器
数据结构·算法·leetcode·双指针·hot100