给定一个单链表,确定它是否是回文。
Input: 1->2
Output: false
Input: 1->2->2->1
Output: true
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null) return true;
ListNode fast = head;
ListNode slow = head;
//fast走到尾部,slow走到中间
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
slow = reserver(slow); //反转
fast = head;
//逐个比较
while(slow != null){
if(fast.val != slow.val){
return false;
}
fast = fast.next;
slow = slow.next;
}
return true;
}
//头插法反转
private ListNode reserver(ListNode head){
ListNode node = null;
while(head != null){
ListNode next = head.next;
head.next = node;
node = head;
head = next;
}
return node;
}
}
利用递归
class Solution {
ListNode node;
public boolean isPalindrome(ListNode head) {
node = head;
return check(head);
}
private boolean check(ListNode head){
if(head == null) return true;
boolean ans = check(head.next); //如果遍历到尾部,向上回溯返回true
boolean iseq = (node.val == head.val) ? true : false; //第i个元素与(n-i)个元素比较
node = node.next;
return ans && iseq;
}
}
LeetCode 234:Palindrome Linked List
原文:https://www.cnblogs.com/le-le/p/12885401.html