力扣热题100之回文链表
题目
给你一个单链表的头节点 head ,请你判断该链表是否为回文链表。如果是,返回 true ;否则,返回 false 。
代码
方法一:
将链表值复制到数组中,在数组中判断是否是回文列表
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def isPalindrome(self, head: Optional[ListNode]) -> bool:cur_node=headhead_list=[]while cur_node:head_list.append(cur_node.val)cur_node=cur_node.nextn=len(head_list)i,j=0,n-1while i<j:if head_list[i]==head_list[j]:i+=1j-=1else:return Falsereturn True
方法二:递归
利用递归回溯过程与从前往后遍历的节点的值进行比较
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def isPalindrome(self, head: Optional[ListNode]) -> bool:self.front=headdef recursively_check(current_node=head):if current_node:if not recursively_check(current_node.next):#递归到最后一个节点,开始回溯return False # 回溯的过程中出现一次False就结束代码if self.front.val != current_node.val:#以下就是回溯时的内容return Falseself.front=self.front.nextreturn Truereturn recursively_check()
方法三:
这个方法的重点就是将这段链表的前后两个部分分开,并翻转后半部分,进行比较
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:def isPalindrome(self, head: Optional[ListNode]) -> bool:first_half_end = self.end_of_first_half(head)second_half_start = self.reverse_list(first_half_end.next)result=True first_position = headsecond_position = second_half_startwhile result and second_position:if first_position.val!=second_position.val:result=Falsefirst_position=first_position.nextsecond_position=second_position.nextfirst_half_end.next=self.reverse_list(second_half_start)return resultdef end_of_first_half(self,head):fast=headslow=headwhile fast.next and fast.next.next:# 确保快指没有针到最后一个节点,并且快指针能够移动两步# 这段代码奇数长度链表:slow 指向正中间的节点。偶数长度链表:slow 指向前半部分的最后一个节点fast=fast.next.nextslow=slow.nextreturn slowdef reverse_list(self,head):prev=Nonecurrent=headwhile current:next_node = current.nextcurrent.next=prevprev=currentcurrent=next_nodereturn prev