Given a singly linked list, determine if it is a palindrome.
思路:两个指针,一个正常递推,另一个递推速度为第一个的两倍(Node.next.next),到末,分两种情况:1.奇数个元素,最后快指针指向最后一个元素(p2.next=null);2.偶数个数,最后快指针指向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 p1 = head,p2 = head;//p1慢指针,p2快指针
while(p2!=null&&p2.next!=null){
p1 = p1.next;
p2 = p2.next.next;
}
if(p2!=null){ //奇数个数
p1 = p1.next;
}
p1 = reverse(p1);//反转后半截链表
while(p1 != null) {
if(head.val != p1.val)return false;
head = head.next;
p1 = p1.next;
}
return p1 == null;
}
public ListNode reverse(ListNode head){
ListNode newHead = null;
while(head!=null){
ListNode next = head.next;
head.next = newHead;
newHead = head;
head = next;
}
return newHead;
}
}