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

相关推荐
slandarer7 分钟前
MATLAB | 趣味编程——动态字符串甜甜圈和爱心
数据结构·matlab·趣味编程
UIU11440 分钟前
P1003 [NOIP 2011 提高组] 铺地毯
数据结构·c++·算法
爱读书的小胖44 分钟前
LeetCode 88. 合并两个有序数组 C 解题分析
c语言·数据结构·算法
inrichtt1 小时前
第七课时:STM32时钟系统揭秘:从零理解时钟树
c语言·数据结构·stm32·单片机·嵌入式硬件
xxwl5852 小时前
区域赛算法模版第四章---数据结构
数据结构·c++·算法
Logic1014 小时前
C语言/数据结构二维数组题解:找出行列O个数均为偶数的格子——奇偶性预处理+二次遍历
c语言·数据结构·算法·二维数组·时间复杂度·动态内存分配·奇偶性
局部有解4 小时前
LeetCode Hot100 438 找到字符串中所有字母异位词
c++·算法·leetcode
垆边人似月.5 小时前
移动长度 k 子串使字符串变成回文
数据结构·算法
David猪大卫5 小时前
【C++修炼】string类:string类的模拟实现
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
jeo陽6 小时前
05-数组与冒泡排序:第一个数据结构与经典算法
c语言·数据结构·算法