首页 > 其他 > 详细

234. Palindrome Linked List

时间:2019-08-21 01:04:12      阅读:85      评论:0      收藏:0      [点我收藏+]

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

* 链表中点查找

* 逆转链表

234. Palindrome Linked List

原文:https://www.cnblogs.com/alison-f/p/11386440.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!