LeetCode-234. 回文链表

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

前半段压栈,后半段出栈,看最后是不是空

# 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 head is None: 
            return True
        a = 0
        test = f = head
        b = []
        while test:
            a += 1
            test = test.next
        if a == 1:
            return True
        a = a//2
        while a>0:
            b.append(f.val)
            f = f.next
            a -= 1
        while f:
            if f.val == b[-1]:
                b.pop()
            f = f.next
        if b:
            return False
        else:
            return True
posted @ 2021-07-17 10:30  小Aer  阅读(2)  评论(0编辑  收藏  举报  来源