/**
* 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 middle = findMiddle(head);
ListNode reverse = reverseList(middle);
while(head != null && reverse != null){
if(head.val != reverse.val){
return false;
}
head = head.next;
reverse = reverse.next;
}
return true;
}
ListNode findMiddle(ListNode head){
if(head == null) return null; //这需要判断单向链表是否为空
ListNode p = head;
while(p.next != null && p.next.next != null){
p = p.next.next;
head = head.next;
}
p = head.next;
head.next = null;
return p;
}
ListNode reverseList(ListNode head){
if(head == null) return null; /这需要判断单向链表是否为空
ListNode pre = head, cur = head.next, nxt = null;
pre.next = null;
while(cur != null){
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}
* 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 middle = findMiddle(head);
ListNode reverse = reverseList(middle);
while(head != null && reverse != null){
if(head.val != reverse.val){
return false;
}
head = head.next;
reverse = reverse.next;
}
return true;
}
ListNode findMiddle(ListNode head){
if(head == null) return null; //这需要判断单向链表是否为空
ListNode p = head;
while(p.next != null && p.next.next != null){
p = p.next.next;
head = head.next;
}
p = head.next;
head.next = null;
return p;
}
ListNode reverseList(ListNode head){
if(head == null) return null; /这需要判断单向链表是否为空
ListNode pre = head, cur = head.next, nxt = null;
pre.next = null;
while(cur != null){
nxt = cur.next;
cur.next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
}