题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param head ListNode类 the head # @return bool布尔型 # def reverseList(head): prev = None current = head while current: next_node = current.next # 保存下一个节点 current.next = prev # 反转当前节点的指针 prev = current # 将prev移动到当前节点 current = next_node # 将current移动到下一个节点 return prev def copyList(head): if not head: return None dummy = new_head = ListNode(head.val) # 创建新链表的虚拟头节点 current = head.next while current: new_head.next = ListNode(current.val) # 创建新节点并链接到新链表 new_head = new_head.next current = current.next return dummy # 返回新链表的头节点(跳过虚拟头节点) class Solution: def isPail(self, head: ListNode) -> bool: # write code here if not head or not head.next: return True node1 = copyList(head) node2 = reverseList(head) while node1: if node1.val == node2.val: node1 = node1.next node2 = node2.next else: return False return True