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

相关推荐
不会就选b4 小时前
算法日常・每日刷题--<链表>3
数据结构·算法·链表
稚南城才子,乌衣巷风流7 小时前
块状链表:数据结构详解与实现
数据结构·链表
闪电悠米7 小时前
力扣hot100-48.旋转图像-转置翻转详解
算法·leetcode·职场和发展
啦啦啦啦啦zzzz8 小时前
算法:贪心算法
c++·算法·leetcode·贪心算法
日拱一卒——功不唐捐9 小时前
红黑树删除(C语言)
c语言·数据结构
不如语冰10 小时前
AI大模型入门-Python进阶-上下文管理与with语句
开发语言·数据结构·数据库·人工智能·pytorch·redis·python
Angle.寻梦10 小时前
数据结构--链表
数据结构·链表
ykdcdc11 小时前
DC-DC隔离和非隔离怎么选?工控/监控/医疗分别用哪种
数据结构·汽车·推荐算法
Angle.寻梦11 小时前
数据结构--堆
数据结构
笨鸟先飞的橘猫14 小时前
redis数据结构学习——stream
数据结构·redis·学习