题目描述
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
进阶: 你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
我的解法——反转一半链表(AC)
- 将链表前半段原地翻转,再将前半段、后半段依次比较,判断是否相等
- 时间时间复杂度均为O(n),空间复杂度为O(1)。
- Beat74%
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
now = head
length = 0
while(now):
length += 1
now = now.next
if(length <= 1):
return True
l1 = None
index = 0
while(index < int(length /2)):
index += 1
temp = head.next
head.next = l1
l1 = head
head = temp
if(length % 2 == 0):
l2 = head
else:
l2 = head.next
while(l1 and l2):
if(l1.val != l2.val):
return False
else:
l1 = l1.next
l2 = l2.next
return True