题解 | #牛群编号的回文顺序#
牛群编号的回文顺序
https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * public ListNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param head ListNode类 * @return bool布尔型 */ public boolean isPalindrome (ListNode head) { // write code here if (head == null || head.next == null) return true; // 1. 快慢指针找中点 ListNode slow = head, fast = head; while (fast.next != null && fast.next.next != null) { slow = slow.next; fast = fast.next.next; } // 2. 逆序中点(奇数节点时slow中点、偶数节点时slow是上中点)之后的链表 ListNode revHead = null, cur = slow.next, next; slow.next = null; while (cur != null) { next = cur.next; cur.next = revHead; revHead = cur; cur = next; } // 3. 头尾比较,判断是否是回文 ListNode p = revHead; cur = head; boolean ans = true; while (cur != null && p != null) { if (cur.val != p.val) { ans = false; break; } cur = cur.next; p = p.next; } // 4. 恢复原链表 ListNode pre = null; cur = revHead; while (cur != null) { next = cur.next; cur.next = pre; pre = cur; cur = next; } slow.next = pre; return ans; } }#链表翻转##链表回文#
线性表基础 文章被收录于专栏
链表、递归、栈