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

相关推荐
数智工坊7 分钟前
【数据结构-栈】3.1栈的顺序存储-链式存储
java·开发语言·数据结构
愚者游世13 分钟前
力扣解决二进制&题型常用知识点梳理
c++·程序人生·算法·leetcode·职场和发展·改行学it
圣保罗的大教堂14 分钟前
leetcode 3640. 三段式数组 II 困难
leetcode
Geoking.17 分钟前
前缀和算法:从一道 LeetCode 题看区间求和优化思想
算法·leetcode·职场和发展
执着25927 分钟前
力扣102、二叉树的层序遍历
数据结构·算法·leetcode
Tisfy29 分钟前
LeetCode 2976.转换字符串的最小成本 I:floyd算法(全源最短路)
算法·leetcode··floyd·题解
元亓亓亓30 分钟前
考研408--数据结构--day5--栈与队列的应用
数据结构·考研··408·队列
v_for_van33 分钟前
力扣刷题记录4(无算法背景,纯C语言)
c语言·算法·leetcode
小高Baby@39 分钟前
Golang中面向对象的三大特性之多态的理解
数据结构·golang
dazzle39 分钟前
Python数据结构(十五):归并排序详解
数据结构·python·算法