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

相关推荐
小poop11 小时前
轮转数组:从暴力到最优,一题掌握算法复杂度分析
数据结构·算法·leetcode
wabs66614 小时前
关于图论【卡码网104.建造最大岛屿的思考】
数据结构·算法·图论
玖玥拾14 小时前
LeetCode 27 移除元素
算法·leetcode
冻柠檬飞冰走茶14 小时前
PTA基础编程题目集 7-15 计算圆周率(C语言实现)
c语言·开发语言·数据结构·算法
hanlin0316 小时前
刷题笔记:力扣第704、977、209题(数组相关)
笔记·算法·leetcode
Rabitebla17 小时前
C++ 内存管理全面复习:从内存分布到 operator new/delete
java·c语言·开发语言·c++·算法·leetcode
玖玥拾17 小时前
LeetCode 58 最后一个单词的长度
算法·leetcode
hanlin0317 小时前
刷题笔记:力扣第19题-删除链表的倒数第N个结点
笔记·leetcode·链表
Tisfy18 小时前
LeetCode 3517.最小回文排列 I:排序(Python两行版) / 计数(O(n)时间+O(C)空间+字符串原地修改)
c语言·python·leetcode·字符串·排序·计数排序·回文
菜鸟的升级路18 小时前
C语言栈刷题:LeetCode 20 有效的括号完整解题笔记
c语言·笔记·leetcode