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

* 链表中点查找

* 逆转链表

转载于:https://www.cnblogs.com/alison-f/p/11386440.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值