Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?
1. Reverse later half part
2. two pointer go through list, one from front and end
public boolean isPalindrome(ListNode head) {
if(head ==null || head.next == null) return true;
//get middle node,
ListNode l1 = head;
ListNode l2 = head;
while(l2.next!=null){
l1 = l1.next;
if(l2.next.next == null){
l2 = l2.next;
break;
}
l2 = l2.next.next;
}
//reverse linked list
l2 = l1.next;
while(l2!=null) {
ListNode l3 = l2.next;
l2.next = l1;
l1 = l2;
l2 = l3;
}//l1 is the last one
//two pointer from front and end
l2 = head;
while(l2 != l1 && l2.next!=l1){
if(l1.val != l2.val)
return false;
l1 = l1.next;
l2 = l2.next;
}
if(l2.next == l1) return l2.val == l1.val;
return true;
}

本文介绍了一种O(n)时间复杂度和O(1)空间复杂度的算法来判断单链表是否为回文串。通过反转链表的后半部分并比较前后两个指针所指向的元素,实现这一目标。
498

被折叠的 条评论
为什么被折叠?



