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

相关推荐
Stardep17 分钟前
算法入门20——二分查找算法——搜索插入位置
数据结构·算法·leetcode
老鼠只爱大米26 分钟前
LeetCode经典算法面试题 #141:环形链表(快慢指针、标记节点等多种方法详细解析)
算法·leetcode·链表·快慢指针·floyd算法·环形链表
踩坑记录1 小时前
leetcode hot100 48.旋转图像 矩阵转置
leetcode
鹿角片ljp1 小时前
力扣112. 路径总和:递归DFS vs 迭代BFS
leetcode·深度优先·宽度优先
im_AMBER1 小时前
Leetcode 104 两两交换链表中的节点
笔记·学习·算法·leetcode
程序员-King.1 小时前
day159—动态规划—打家劫舍(LeetCode-198)
c++·算法·leetcode·深度优先·回溯·递归
浅念-1 小时前
C语言——单链表
c语言·开发语言·数据结构·经验分享·笔记·算法·leetcode
夏乌_Wx1 小时前
练题100天——DAY40:合并两个有序链表
数据结构
hans汉斯2 小时前
建模与仿真|基于GWO-BP的晶圆机器人大臂疲劳寿命研究
大数据·数据结构·算法·yolo·机器人·云计算·汉斯出版社
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——力扣 127 题:单词接龙
算法·leetcode·职场和发展