234. Palindrome Linked List

Easy

https://leetcode.com/problems/palindrome-linked-list/

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

Example 1:

Input: 1->2

Output: false

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

方法一:遍历链表,把值依次存在数组中,然后对数组判断是否对称。时间 O(n),空间 O(n)

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: bool
 6         """
 7         if not head: 
 8             return True
 9         num = []
10         while head:
11             num.append(head.val)
12             head = head.next
13         i, j = 0, len(num)-1
14         while i<j:
15             if num[i]!=num[j]:
16                 return False
17             i += 1
18             j -= 1
19         return True

 

方法二:先用快慢指针找到链表中点,然后逆转链表后半段,比较前半段和逆转后的后半段,若相同则对称。时间 O(n),空间 O(1)

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: bool
 6         """
 7         if not head: 
 8             return True
 9         mid = findMid(head)
10         mid.next = reverseLinkedList(mid.next)
11         p,q = head, mid.next
12         while q and p.val==q.val:
13             p = p.next
14             q = q.next
15         return False if q else True
16     
17 def findMid(head):
18     slow = head
19     fast = head.next
20     while fast and fast.next:
21         fast = fast.next.next
22         slow = slow.next
23     return slow
24 
25 def reverseLinkedList(head):
26     pre = None
27     while head:
28         temp = head.next
29         head.next = pre
30         pre = head
31         head = temp
32     return pre

* 链表中点查找

* 逆转链表

posted @ 2019-08-21 00:18  Aparecium  阅读(135)  评论(0编辑  收藏  举报