234. Palindrome Linked List

Easy數組

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

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

Example 1:指針

Input: 1->2 code

Output: falseblog

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

方法一:遍歷鏈表,把值依次存在數組中,而後對數組判斷是否對稱。時間 O(n),空間 O(n)get

 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)it

 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

* 鏈表中點查找io

* 逆轉鏈表

相關文章
相關標籤/搜索