回文链表(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

相关推荐
smj2302_796826521 天前
解决leetcode第3943题递增后的数对数量
数据结构·python·算法·leetcode
梓䈑1 天前
【算法题攻略】快速排序 和 归并排序
数据结构·c++·排序算法
医用门1 天前
医院用门一线品牌
leetcode
he___H1 天前
leetcode100-普通数组
java·数据结构·算法·leetcode
不知名的老吴1 天前
经典算法实战:重新排列日志文件(二)
数据结构·算法
CS创新实验室1 天前
数据结构和算法:斐波那契堆
数据结构·算法·斐波那契堆
guslegend1 天前
2.Redis核心数据结构
数据结构·数据库·redis
Daydream.V1 天前
Redis 零基础入门到实战:数据结构 + 常用命令 + 场景全覆盖
数据结构·数据库·redis
bnmoel1 天前
数据结构深度剖析二叉树・中篇:堆的概念及结构 ,实现应用全解析
数据结构·算法·二叉树··top-k问题
fu的博客1 天前
【数据结构15】哈夫曼树构建、编码(附手绘图解)
数据结构