题解 | #牛群编号的回文顺序#
牛群编号的回文顺序
https://www.nowcoder.com/practice/e41428c80d48458fac60a35de44ec528
题目考察的知识点:
这道题目主要考察了链表操作、快慢指针的应用,以及判断回文序列的方法。
题目解答方法的文字分析:
我们需要判断链表的编号顺序是否是回文的。使用快慢指针,找到链表的中点。快指针每次移动两步,慢指针每次移动一步,当快指针到达末尾时,慢指针会在链表的中点停下。反转链表的后半部分,以便与前半部分进行比较。可以使用一个指针来辅助反转链表。逐个比较前半部分和反转后的后半部分的值,如果所有值都匹配,则链表是回文的,返回 true;否则返回 false。
本题解析所用的编程语言:
这个题解使用了 Java 编程语言。
完整且正确的编程代码:
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) {
if (head == null || head.next == null) {
return true;
}
// Step 1: Find the middle of the list
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// Step 2: Reverse the second half of the list
ListNode prev = null;
ListNode current = slow;
while (current != null) {
ListNode nextTemp = current.next;
current.next = prev;
prev = current;
current = nextTemp;
}
slow = prev;
// Step 3: Compare the first half with the reversed second half
while (slow != null) {
if (head.val != slow.val) {
return false;
}
head = head.next;
slow = slow.next;
}
return true;
}
}

海康威视公司福利 1182人发布
查看5道真题和解析