lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

  • leetcode

    • 数组

    • 位运算

    • 动态规划

    • 链表

      • 21. 合并两个有序链表
      • 141. 环形链表
      • 142. 环形链表 II
      • 160. 相交链表
      • 203. 移除链表元素
      • 206. 反转链表
      • 234.回文链表
    • 栈

    • 树

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • leetcode
  • list
2023-04-29

回文链表

https://leetcode-cn.com/problems/palindrome-linked-list/ (opens new window) 需要注意的点 第一种,遍历链表得到数组,复制数组的相反副本,比较数组的值 第二种,快慢指针

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:

        if head is None:
            return False
        l = []
        while head is not None:
            l.append(head.val)
            head = head.next
        
        l1 = l[::-1]
        return l1 == l
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        slow = head
        fast = head
        # 推进快慢指针(节点)
        # 快节点一次两步,慢节点一次一步
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next

        # 如果快节点不是Null,说明慢节点在中心点
        if fast is not None:
            slow = slow.next
        
        left = head
        right = self.reverseList(slow)

        while right is not None:
            if left.val != right.val:
                return False

            left = left.next
            right = right.next
        
        return  True

        '''
            反转链表
        '''
    def reverseList(self, node: ListNode) -> ListNode:
        pre = None
        cur = node
        while cur is not None:
            next = cur.next
            cur.next = pre
            pre = cur
            cur = next

        return pre
206. 反转链表
20.有效的括号

← 206. 反转链表 20.有效的括号→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式