原题网址:https://leetcode.com/submissions/detail/58253344/
Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
慢指针最后停在的位置,就是前段链表拆分后的链表头,后段链表的链表头,需要根据节点个数是奇数还是偶数会有差异,需要分开处理。
/**
* 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) {
if (head == null || head.next == null) return true;
ListNode slow = head;
ListNode next = head.next;
ListNode fast = head.next;
head.next = null;
while (fast.next != null && fast.next.next != null) {
fast = fast.next.next;
ListNode prev = slow;
slow = next;
next = next.next;
slow.next = prev;
}
ListNode n1 = slow;
ListNode n2 = fast.next == null ? next : next.next;
while (n1 != null) {
if (n1.val != n2.val) return false;
n1 = n1.next;
n2 = n2.next;
}
return true;
}
}
另一个类似的方法:
/**
* 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 slow = head;
ListNode prev = null;
ListNode fast = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
ListNode next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
fast = fast == null ? slow : slow.next;
slow = prev;
while (slow != null) {
if (slow.val != fast.val) return false;
slow = slow.next;
fast = fast.next;
}
return true;
}
}