LeetCode--234--回文链表

问题描述:

请判断一个链表是否为回文链表。

示例 1:

输入: 1->2
输出: false

示例 2:

输入: 1->2->2->1
输出: true

方法1:用列表把前半部分保存起来,指针p从中间开始进行比较。

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: bool
 6         """
 7         p = head
 8         length = 0
 9         while p:
10             p = p.next
11             length += 1
12         p = head
13         i = 0
14         nums = []
15         while i < length // 2 and p:
16             nums.append(p.val)
17             p = p.next
18             i += 1
19         if length % 2 == 1:
20             p = p.next
21         nums = nums[::-1]
22         for i in nums:
23             if i != p.val:
24                 return False
25             p = p.next
26         return True

方法2:把全部的数都取出来放到list中,正序和逆序进行比较。

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: bool
 6         """
 7         cur=head
 8         array=[]
 9         while cur:
10             array.append(cur.val)
11             cur=cur.next
12         return array==array[::-1]

方法3:(官网)*

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         rev = None
 4         slow = fast = head
 5         while fast and fast.next:
 6             fast = fast.next.next
 7             rev, rev.next, slow = slow, rev, slow.next
 8         if fast:
 9             slow = slow.next
10         while rev and rev.val == slow.val:
11             slow = slow.next
12             rev = rev.next
13         return not rev

方法4:转

 1 class Solution(object):
 2     def isPalindrome(self, head):
 3         """
 4         :type head: ListNode
 5         :rtype: bool
 6         """
 7         if not head or not head.next:
 8             return True
 9 
10         # 快慢指针法找链表的中点
11         slow = fast = head
12         while fast.next and fast.next.next:
13             slow = slow.next
14             fast = fast.next.next
15 
16         slow = slow.next # slow指向链表的后半段
17         slow = self.reverseList(slow)
18 
19         while slow:
20             if head.val != slow.val:
21                 return False
22             slow = slow.next
23             head = head.next
24         return True
25 
26     def reverseList(self, head):
27         new_head = None
28         while head:
29             p = head
30             head = head.next
31             p.next = new_head
32             new_head = p
33         return new_head

2018-09-20 14:51:27

原文地址:https://www.cnblogs.com/NPC-assange/p/9680944.html