Given a singly linked list, determine if it is a palindrome.

Follow up:
Could you do it in O(n) time and O(1) space?

思路

最简单的方法当然是把链表里面的所有元素放在数组里,然后就可以判断这个链表是不是回文的了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 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
"""
cur = head
res = []
while (cur):
res.append(cur.val)
cur = cur.next
length = len(res)
for i in range(length):
if (res[i] != res[-i-1]):
return False
return True

其实还可以利用快慢指针,找到链表的中点;与此同时,慢指针将链表前一半进行反转。之后,再逐节点进行比较,判断链表是否为回文。

但是有人指出,反转链表并不能使得空间复杂度为O(1)。具体请参见:

https://discuss.leetcode.com/topic/18533/reversing-a-list-is-not-considered-o-1-space