234. Palindrome Linked List
Given a singly linked list, determine if it is a palindrome.
public class Solution {
public boolean isPalindrome(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
if (fast != null) {
slow = slow.next; //如1234321,则slow指向第二个3,如果是12344321则slow指向第二个4
}
slow = reverse(slow);//把321翻转成123
fast = head;//fast指向开头的1
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;
}
}
浙公网安备 33010602011771号