LeetCode:234. 回文链表
1、题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2 输出: false
示例 2:
输入: 1->2->2->1 输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
2、题解
2.1、解法一
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def get_elem(self,head): n = head ret = [] while n: ret.append(n.val) n = n.next return ret def isPalindrome(self, head): """ :type head: ListNode :rtype: bool """ ret = self.get_elem(head) if len(ret) == 0 or len(ret) == 1: return True mid = len(ret)//2 if len(ret)%2 == 0: left = ret[:mid] right = ret[mid:] right.reverse() else: left = ret[:mid] right = ret[mid+1:] right.reverse() if left == right: return True return False