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

相关推荐
载数而行5206 分钟前
算法系列2之最短路径
c语言·数据结构·c++·算法·贪心算法
fu的博客13 分钟前
【数据结构10】满/完全二叉树、顺序/链式存储
数据结构·
逆境不可逃1 小时前
【除夕篇】LeetCode 热题 100 之 189.轮转数组
java·数据结构·算法·链表
美好的事情能不能发生在我身上1 小时前
Leetcode热题100中的:哈希专题
算法·leetcode·哈希算法
wefg11 小时前
【算法】倍增思想(快速幂)
数据结构·c++·算法
Zik----2 小时前
Leetcode24 —— 两两交换链表中的节点(迭代法)
数据结构·算法·链表
!停2 小时前
数据结构二叉树—链式结构(下)
数据结构·算法
逆境不可逃2 小时前
LeetCode 热题 100 之 41.缺失的第一个正数
算法·leetcode·职场和发展
666HZ6663 小时前
数据结构5.0 树与二叉树
数据结构
We་ct3 小时前
LeetCode 173. 二叉搜索树迭代器:BSTIterator类 实现与解析
前端·算法·leetcode·typescript