• 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

    总结

    这真的是简单吗?

  • 相关阅读:
    逻辑运算符的优先级
    C# 使用DocX生成word文档
    python基础之函数模块的导入
    Nodejs进程间通信
    Springboot毕设项目环球视野网站92i41(java+VUE+Mybatis+Maven+Mysql)
    Spring | Bean自动装配详解
    要使用API接口获取淘宝电商平台的数据,您需要遵循以下步骤:
    AHB、APB详解和FCLK,PCLK,HCLK详解
    python3.5版本使用openpyxl报‘NoneType‘ object has no attribute ‘read‘问题
    每日一题day7-1652. 拆炸弹
  • 原文地址:https://blog.csdn.net/m0_61661179/article/details/128201852