题目描述
Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2
Output: false
Example 2:
Input: 1->2->2->1
Output: true
方法思路
class Solution {
//Runtime: 1 ms, faster than 97.83% of Java online submissions for Palindrome Linked List.
public boolean isPalindrome(ListNode head) {
ListNode fast = head, slow = head;
//称正读和反读都相同的字符序列为“回文”,如“abba”、“abccba”、12321、123321是“回文”。
while (fast != null && fast.next != null) {
//判断条件里不能有fast.next.next != null,因为当只有一个结点时,会出现空指针异常
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) {
// odd nodes: let right half smaller,针对奇数个元素的情况
//因为奇数的时候,最中间的结点不需要判定
slow = slow.next;
}
slow = reverse(slow);
fast = head;
while (slow != null) {
if (fast.val != slow.val) {
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
public ListNode reverse(ListNode head) {
//反转单链表
ListNode prev = null;
while (head != null) {
ListNode next = head.next;
head.next = prev;
prev = head;
head = next;
}
return prev;
}
}