• LeetCode234(Python)—— 回文链表(简单)


    回文链表

    概述:给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false

    1. 输入:head = [1,2,2,1]
    2. 输出:true
    3. 输入:head = [1,2]
    4. 输出:false

    方法一:遍历+检索

    思路:核心思路是把单链表存储出来,然后进行回文数的判断即可。

    1. # 遍历+检索
    2. # 核心思路是把单链表存储出来,然后进行回文数的判断即可。
    3. class Solution:
    4. def isPalindrome(self, head: Optional[ListNode]) -> bool:
    5. ans = []
    6. while head:
    7. ans.append(head.val)
    8. head = head.next
    9. return ans == ans[::-1]

    方法二:递归

    思路:指向头尾两个节点,然后依次判断即可。

    1. # 递归
    2. # 指向头尾两个节点,然后依次判断即可。
    3. class Solution:
    4. def isPalindrome(self, head: Optional[ListNode]) -> bool:
    5. self.front_pointer = head
    6. def recursively_check(current_node = head):
    7. if current_node is not None:
    8. if not recursively_check(current_node.next):
    9. return False
    10. if self.front_pointer.val != current_node.val:
    11. return False
    12. self.front_pointer = self.front_pointer.next
    13. return True
    14. return recursively_check()

    方法三:反转链表

    思路:此算法比较难想,核心在于找到尾节点并反转链表进行判断,然后恢复原有链表,返回即可。

    1. # 反转链表
    2. # 此算法比较难想,核心在于找到尾节点并反转链表进行判断,然后恢复原有链表,返回即可。
    3. class Solution:
    4. def isPalindrome(self, head: ListNode) -> bool:
    5. if head is None:
    6. return True
    7. first_half_end = self.end_of_first_half(head)
    8. second_half_start = self.reverse_list(first_half_end.next)
    9. result = True
    10. first_position = head
    11. second_position = second_half_start
    12. while result and second_position is not None:
    13. if first_position.val != second_position.val:
    14. result = False
    15. first_position = first_position.next
    16. second_position = second_position.next
    17. first_half_end.next = self.reverse_list(second_half_start)
    18. return result
    19. def end_of_first_half(self, head):
    20. fast = head
    21. slow = head
    22. while fast.next is not None and fast.next.next is not None:
    23. fast = fast.next.next
    24. slow = slow.next
    25. return slow
    26. def reverse_list(self, head):
    27. previous = None
    28. current = head
    29. while current is not None:
    30. next_node = current.next
    31. current.next = previous
    32. previous = current
    33. current = next_node
    34. return previous

    总结

    这真的是简单吗?

  • 相关阅读:
    [附源码]Python计算机毕业设计Django宁财二手物品交易网站
    mysql之squid代理服务器
    跨境电商与支付介绍
    葡萄糖-聚乙二醇-6-羧甲基荧光素 Glucose-PEG-6-FAM
    android 关于admob聚合applovin的坑
    七大排序。。。
    Java学习笔记3.9.1 Lambda表达式 - Lambda表达式入门
    MQ系列6:消息的消费
    Windows系统部署Serva PXE网络引导安装操作系统
    【密评】商用密码应用安全性评估从业人员考核题库(七)
  • 原文地址:https://blog.csdn.net/m0_61661179/article/details/128201852