-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquestion_5.py
More file actions
41 lines (35 loc) · 865 Bytes
/
question_5.py
File metadata and controls
41 lines (35 loc) · 865 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python
# @Time : 2018/5/5 下午7:28
# @Author : cancan
# @File : question_5.py
# @Function : 回文链表
"""
Question:
请检查一个链表是否为回文链表。
Follow up:
你能在 O(n) 的时间和 O(1) 的额外空间中做到吗
"""
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return True
t = [head.val]
n = head.next
while n:
t.append(n.val)
n = n.next
l = len(t)
i = l // 2
if l % 2 == 0:
return t[:i] == t[i:][::-1]
else:
return t[:i] == t[i + 1:][::-1]