https://leetcode.com/problems/palindrome-linked-list/
對input進行修改,後半段反轉。但是反轉連結清單還是不熟啊,這怎麼行!!!反轉之後的尾節點的next為null。剩下看注釋
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
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;
}
// 總結點數為奇數,為滿足下方while判斷,slow要後移一位
if (fast != null) {
slow = slow.next;
}
ListNode tail = reverse(slow);
// 不能是head != null,因為前半段的尾節點未置為空
while (tail != null) {
if (tail.val != head.val) {
return false;
}
tail = tail.next;
head = head.next;
}
return true;
}
private ListNode reverse(ListNode head) {
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}