Given a singly linked list, determine if it is a palindrome.
Example 1:
Input: 1->2 Output: false
Example 2:
Input: 1->2->2->1 Output: true
解决回文问题,关键是利用对称性,用首尾两个指针依次遍历链表,比较val的大小是否相等
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null)
return true;
if(head.next == null)
return true;
ListNode tail = head;
while (tail.next != null){
tail = tail.next;
}
if(head.val != tail.val)
return false;
if(head.next == tail)
return true;
while(head.next != null && tail != null) {
head = head.next;
ListNode newTail = head;
while(newTail.next != tail) {
newTail = newTail.next;
}
newTail.next = null;
tail = newTail;
if(head.val != tail.val)
return false;
if(head.next == tail)
return true;
}
return true;
}
}