题目:
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶:
你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
解法
(1)将链表元素转成数组list
(2)判断list是不是回文list,判断第i位和len - i是否相等即可
代码如下:
# 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
"""
list = []
while head != None:
list.append(head.val)
head = head.next
length = len(list)
for i in range(length / 2):
if list[i] != list[length - 1 - i]:
return False
return True
时间复杂度:O(n)
空间复杂度:O(n)
奥利给!
补:一行代码判断回文数组list
代码如下:
# 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
"""
list = []
while head != None:
list.append(head.val)
head = head.next
# length = len(list)
# for i in range(length / 2):
# if list[i] != list[length - 1 - i]:
# return False
# return True
return list == list[::-1]