题目:
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?
题意:
判断一个单链表是否为回文串,要求用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 head == None or head.next == None :
return True
else :
#快慢指针法寻找单链表的中间节点
fast = ListNode(0)
slow = ListNode(0)
new_head = ListNode(0)
fast = head
slow = head
while fast != None and fast.next != None :
slow = slow.next
fast = fast.next.next
#判断单链表节点个数,如果fast不为空,则为奇数个;如果fast为空,则为偶数个
if fast != None : #奇数个时,slow指向中间节点,将slow之后的节点反转
new_head = slow.next
else :
new_head = slow
#反转new_head之后的链表
p = ListNode(0)
q = ListNode(0)
p = new_head.next
q = new_head
new_head.next = None
while p != None :
q = p.next
p.next = new_head
new_head = p
p = q
#比较head和newhead是否是回文串
p = head
q = new_head
while q != None :
if p.val != q.val :
return False
p = p.next
q = q.next
return True
笔记:
1、学到用快慢指针法寻找单链表的中间节点,参考:http://blog.csdn.net/sunao2002002/article/details/46918645
2、反转单链表,比较是否为回文串