题目:请判断一个链表是否为回文链表。你能否用 O(n) 时间复杂度和 O(1) 空间复杂度解决此题?
示例:
输入: 1->2
输出: false
输入: 1->2->2->1
输出: true
思路:先遍历一遍链表得到链表长度,然后从链表中间开始将后半段反转,然后从两个链表头依次判断当前节点是否相同,若相同则挑战到下一个节点,不相同则返回false。
代码:
# 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
"""
temp = head
lenth = 0
while temp:
lenth += 1
temp = temp.next
if lenth <=1 :
return True
bhead = head
for i in range(lenth//2):
bhead = bhead.next
if not bhead.next == None:
pre = None
cur = bhead
nxt = bhead.next
while not nxt == None:
cur.next = pre
pre = cur
cur = nxt
nxt = nxt.next
cur.next = pre
bhead = cur
for i in range(lenth//2):
if head.val == bhead.val:
head = head.next
bhead = bhead.next
else:
return False
return True