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

相关推荐
硕风和炜5 小时前
【LeetCode: 2492. 两个城市间路径的最小分数 + DFS】
java·算法·leetcode·深度优先·dfs·bfs·并查集
凯瑟琳.奥古斯特8 小时前
K次取反最大化数组和解法(力扣1005)
开发语言·c++·算法·leetcode·职场和发展
tachibana210 小时前
hot100 回文链表(234)
java·网络·数据结构·leetcode·链表
aaaameliaaa10 小时前
进制练习题【找出只出现一次的数字、交换两个变量(不创建临时变量)、统计二进制中1的个数、打印整数二进制的奇数位和偶数位、求两个数二进制中不同位的个数】
c语言·数据结构·笔记·算法
-dzk-10 小时前
【系统架构设计师】案例分析篇
开发语言·数据结构·python·算法·架构·系统架构·架构设计
wabs66612 小时前
关于动态规划【力扣1143.最长公共子序列的思考】
算法·leetcode·动态规划
剑挑星河月13 小时前
54.螺旋矩阵
java·算法·leetcode·矩阵
东华万里13 小时前
第30篇 代码习惯 初学C与数据结构有感
c语言·数据结构·大学生专区
星空露珠14 小时前
迷你世界UGc3.0脚本Wiki[剧情动画模块管理接口 Timeline]
开发语言·数据结构·算法·游戏·lua
笨笨没好名字14 小时前
Leetcode刷题python3版第一周(下)
linux·算法·leetcode