编写一个函数,检查输入的链表是否是回文的。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:双指针
我们知道一个有向链表中,是不能指向前一个指针的,所以我们遍历链表,把链表的值储存在数组中,然后反向数组,最后判断反向数组与数组是否相等,相等即为回文。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
a=[]
node=head
while node:
a.append(node.val)
node=node.next
if a==a[::-1]:
return True
else:
return False
方法二:快慢指针
1,采用快慢两个指针去寻找链表的中间节点,快指针一次走2位,慢指针一次走1位,快指针遍历完之后慢指针所指位链表中心节点。;
2,根据链表的中间节点反转后一半的链表;
3,迭代比较链表前一半的元素和后一半的元素,判断节点的值是否相等,得出是否为回文。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
# 使用列表存储,然后逆转比较
'''
vals = []
cur = head
while cur:
vals.append(cur.val)
cur = cur.next
return vals == vals[::-1]
'''
# 使用快慢指针,找到中间节点,反转后半部分,比较
if head is None:
return True
first = self.find(head)
second = self.reverse(first.next)
flag = True
first_position = head
second_position = second
while flag and second_position:
if first_position.val != second_position.val:
flag = False
first_position = first_position.next
second_position = second_position.next
# 还原链表
first.next = self.reverse(second)
return flag
# 快慢指针找链表中点
def find(self,head):
fast = head
slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
def reverse(self,head):
previous = None
cur = head
while cur:
next_node = cur.next
cur.next = previous
previous = cur
cur = next_node
return previous
代码参照:
作者:lian-zhou
链接:https://leetcode-cn.com/problems/palindrome-linked-list-lcci/solution/kuai-man-zhi-zhen-jie-jue-by-lian-zhou/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。