题解 | 判断一个链表是否为回文结构
判断一个链表是否为回文结构
https://www.nowcoder.com/practice/3fed228444e740c8be66232ce8b87c2f
import java.util.Scanner;
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
if (n == 0) {
System.out.println(true);
return;
}
ListNode head = new ListNode(scanner.nextInt());
ListNode current = head;
for (int i = 1; i < n; i++) {
current.next = new ListNode(scanner.nextInt());
current = current.next;
}
System.out.println(isPalindrome(head));
}
public static boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
// 1. 使用快慢指针找到中间节点
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 2. 反转后半部分链表
ListNode secondHalf = reverse(slow);
// 3. 比较前半部分和反转后的后半部分
ListNode p1 = head;
ListNode p2 = secondHalf;
while (p2 != null) {
if (p1.val != p2.val) {
return false;
}
p1 = p1.next;
p2 = p2.next;
}
return true;
}
private static ListNode reverse(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
}
查看7道真题和解析