首页 > 试题广场 >

判断一个链表是否为回文结构

[编程题]判断一个链表是否为回文结构
  • 热度指数:188996 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个链表,请判断该链表是否为回文结构。
回文是指该字符串正序逆序完全一致。
数据范围: 链表节点数 ,链表中每个节点的值满足
示例1

输入

{1}

输出

true
示例2

输入

{2,1}

输出

false

说明

2->1     
示例3

输入

{1,2,2,1}

输出

true

说明

1->2->2->1     

说明:本题目包含复杂数据结构ListNode,点此查看相关信息
先转成数组,再利用回文数组翻转前后保持一致的性质去判断即可

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head ListNode类 the head
# @return bool布尔型
#
class Solution:
    def isPail(self , head: ListNode) -> bool:
        # write code here
        if not head:
            return head
        pre = head
        nums = []
        while pre is not None:
            val = pre.val
            pre = pre.next
            nums.append(val)
        if nums == nums[::-1]:
            return True
        return False


发表于 2024-04-21 10:50:03 回复(0)
class Solution:
def isPail(self , head: ListNode) -> bool:
# write code here
list_head = []
while head:
list_head.append(head.val)
head = head.next
for i in range(len(list_head)):
if i>len(list_head)-1-i:
break
if list_head[i] != list_head[len(list_head)-1-i]:
return False
return True
发表于 2023-08-21 22:44:08 回复(0)
class Solution:
    def isPail(self , head: ListNode) -> bool:
        # write code here
        list1 = []
        while head != None:
            list1.append(head.val)
            head = head.next
        print(list1)
        left = 0
        right = len(list1)-1
        while left < right:
            if list1[left] != list1[right]:
                return False
            left += 1
            right -= 1
        return True

发表于 2023-08-17 11:47:06 回复(0)
class Solution:
    def isPail(selfhead: ListNode) -> bool:
        # write code here
        list1 = []
        while head != None:
            list1.append(head)
            head = head.next
        n = len(list1)
        if n==0:
            return False
        for i in range(int(n/2) +1):
            if list1[i].val != list1[n - i - 1].val:
                return False
        return True

发表于 2022-10-18 17:15:51 回复(0)

class Solution:
    def isPail(self , head ):
        # write code here
        alist = []
        while(head!=None):
            alist.append(head)
            head = head.next
        n = len(alist)
        if n==0:
            return False
        for i in range((n-1)/2+1):
            if alist[i].val!=alist[n-i-1].val:
            
                return False
        return True 

发表于 2022-03-20 19:42:30 回复(0)
class Solution:
    def isPail(self , head: ListNode) -> bool:
        res = []
        cur = head 
        while cur:
            res.append(cur.val)
            cur = cur.next
        return res == res[::-1]

发表于 2021-11-14 11:03:58 回复(0)