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

相关推荐
滴滴答滴答答1 小时前
LeetCode Hot100 之 17 合并区间
算法·leetcode·职场和发展
ccLianLian1 小时前
数据结构·链表的数组实现
数据结构·链表
梦游钓鱼2 小时前
c++中一维数组和二维数组的应用
数据结构·c++·算法
郝学胜-神的一滴3 小时前
深入解析Effective Modern C++条款35:基于任务与基于线程编程的哲学与实践
开发语言·数据结构·c++·程序人生
望舒5134 小时前
代码随想录day32,动态规划part1
java·算法·leetcode·动态规划
楠秋9204 小时前
代码随想录算法训练营第三十二天| 509. 斐波那契数 、 70. 爬楼梯 、746. 使用最小花费爬楼梯
数据结构·算法·leetcode·动态规划
㓗冽4 小时前
最大效益(二维数组)-基础题76th + 螺旋方阵(二维数组)-基础题77th + 方块转换(二维数组)-基础题78th
数据结构·算法
We་ct4 小时前
LeetCode 25. K个一组翻转链表:两种解法详解+避坑指南
前端·算法·leetcode·链表·typescript
Hag_204 小时前
LeetCode Hot100 438.找到字符串中的所有字母异位词
算法·leetcode·职场和发展
元亓亓亓4 小时前
LeetCode热题100--239. 滑动窗口最大值--困难
数据结构·算法·leetcode