234.Given a singly linked list, determine if it is a palindrome.
这个代码时间复杂度和空间复杂度虽然不咋地,但是,这个想法很优秀,用递归实现了链表的倒序,自己画一下运行步骤,一下子就看出来了。
class Solution {
ListNode first = null;
public boolean isPalindrome(ListNode head) {
if (head == null || head.next == null) {
return true;
}
first = head;
return helper(head);
}
private boolean helper(ListNode root) {
if (root == null) {
return true;
}
boolean flag = helper(root.next);
if (first.next == null) {
return true;
}
if (first.val != root.val) {
return false;
}
first = first.next;
return flag;
}
}
目标:每天一道算法题。
时间:2019-6-1
已完成:7道