leetcode-234:回文链表

简介: leetcode-234:回文链表

题目

题目链接

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

解题

方法一:转换为列表

把链表的值放入到列表中, 判断列表是否为回文列表

# 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:
        vals = []
        cur = head
        while cur:
            vals.append(cur.val)
            cur = cur.next
        return vals==vals[::-1]

复杂度分析:

  • 时间复杂度:O(n)O(n),其中 nn 指的是链表的元素个数。
  • 空间复杂度:O(n)O(n),其中 nn 指的是链表的元素个数,我们使用了一个数组列表存放链表的元素值。

方法二:双指针

将后半段链表反转,比如原来2→3→4→3→2变成2→3→4←3←2

然后一个指针从头开始,另一个指针从尾巴开始,到中间为止,遍历过程中假如值都相等,那么就是回文链表。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if not head:
            return True
        fast=head.next
        slow=head
        # 找到前后半段分水岭
        while fast and fast.next:
            fast=fast.next.next
            slow=slow.next
        #此时slow指向前一半的最后一个(偶数) 或者 中间结点(奇数)
        cur=slow.next
        # 将后半段就地逆置
        pre=None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        # 开始比较
        p=head
        q=pre
        while q:
            if q.val==p.val:
                q=q.next
                p=p.next
            else:
                return False
        return True
相关文章
|
2月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
2月前
|
算法
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
LeetCode刷题---19. 删除链表的倒数第 N 个结点(双指针-快慢指针)
|
2月前
|
存储
LeetCode刷题---817. 链表组件(哈希表)
LeetCode刷题---817. 链表组件(哈希表)
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
2月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
2月前
|
算法 安全 数据处理
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
LeetCode刷题---707. 设计链表(双向链表-带头尾双结点)
|
15天前
【力扣】409.最长回文串
【力扣】409.最长回文串
|
16天前
【力扣】21. 合并两个有序链表
【力扣】21. 合并两个有序链表
|
2月前
|
存储 JavaScript
leetcode82. 删除排序链表中的重复元素 II
leetcode82. 删除排序链表中的重复元素 II
22 0
|
2月前
leetcode83. 删除排序链表中的重复元素
leetcode83. 删除排序链表中的重复元素
10 0

热门文章

最新文章