回文链表-python

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

思考:对称结构要想到stack

方案一:双指针法

将节点值赋值到数组中,使用双指针依次比较元素

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def isPalindrome(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        vals = []
        # 不要破坏head节点
        current_node = head
        while current_node is not None:
            vals.append(current_node.val)
            current_node = current_node.next
        # 比较逆转后两个list是否相同
        return vals == vals[::-1]

 

posted @ 2022-12-03 20:59  今夜无风  阅读(23)  评论(0编辑  收藏  举报