题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 the head * @return bool布尔型 */ public ListNode copy(ListNode head) { if (head == null) return null; // 创建一个新的头节点 ListNode newHead = new ListNode(head.val); ListNode current = newHead; ListNode originalCurrent = head.next; // 复制原链表的每个节点,并链接到新链表上 while (originalCurrent != null) { current.next = new ListNode(originalCurrent.val); current = current.next; originalCurrent = originalCurrent.next; } return newHead; } public boolean isPail (ListNode head) { // 法一:翻转链表后对比两个链表是否相等 if (head == null || head.next == null) { return true; } ListNode head1 = copy(head); ListNode pre = null; ListNode cur = head; ListNode res = cur; while (cur != null) { ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } while (pre != null && head1 != null) { if (pre.val != head1.val) { return false; } head1 = head1.next; pre = pre.next; } return pre == null && head1 == null; } }
链表翻转后逐个元素判断是否相等