题解 | #判断一个链表是否为回文结构#
判断一个链表是否为回文结构
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 boolean isPail (ListNode head) { // write code here if (head == null) { return true; } ListNode p1 = head; ListNode p2 = head; while (p2 != null) { p2 = p2.next; if (p2 != null) { p2 = p2.next; p1 = p1.next; } } ListNode linkListHead2 = revertLinkList(p1); p1 = head; p2 = linkListHead2; while (p1 != null && p2 != null) { if (p1.val != p2.val) { return false; } p1 = p1.next; p2 = p2.next; } return true; } public static ListNode revertLinkList(ListNode head) { /*设定几个变量:当前节点指针,新链表头节点指针 遍历每一个节点,当遍历到一个节点时: 1.保存该节点的next指针 2.令当前节点的next指针指向新链表头节点 3.将新链表的头节点指针指向当前节点 4.将当前节点指针指向第一步保存的next指针*/ ListNode currentNode = head; ListNode newLinkListHead = null; while (currentNode != null) { ListNode nextNode = currentNode.next; currentNode.next = newLinkListHead; newLinkListHead = currentNode; currentNode = nextNode; } return newLinkListHead; } }