给定一个单链表,判断它是否是回文。
输入: 1->2
输出: false
输入: 1->2->2->1
输出: true
判断链表是否为回文,可以通过翻转链表后半部分并比较两半部分是否相同来实现。具体步骤如下:
class Solution {
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// 将中间节点归属到前半部分
if (fast != null) {
slow = slow.next;
}
slow = reverseList(slow);
fast = head;
while (slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
private ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
希望这篇博客对你有帮助。如有任何疑问或建议,欢迎留言交流。