这是我对问题的尝试解决方案。
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null)
return true;
ListNode hare = head;
ListNode tort = head;
while(hare!=null && hare.next!=null) {
//System.out.print("Hare "+ hare.val +"tort "+tort.val);
hare = hare.next.next;
tort = tort.next;
}
//Tort is the middle of the list
reverseLL(tort);
ListNode tmp = tort;
printList(tmp);
while(tort!=null) {
if(head.val!=tort.val)
return false;
head = head.next;
tort = tort.next;
continue;
}
return true;
}
private ListNode reverseLL(ListNode head) {
if(head == null || head.next == null) {
return head;
}
ListNode nextElem = head.next;
//System.out.println("Processing "+head.val);
head.next = null;
ListNode rev = reverseLL(nextElem);
nextElem.next = head;
return rev;
}
private void printList(ListNode head){
while(head!=null){
System.out.println("[" +head.val + "]");
head = head.next;
}
}
但我注意到一些我无法弄清楚的非常奇怪的事情。tort当前结束于链表的中间。然而,从头到尾的逆转tort似乎将侵权行为与链表的其余部分断开。
例如,如果输入是 1->2->3->4,tort 最终是 3,但是在从 tort 反转它之后打印列表只打印 3,即。3 与列表的其余部分断开连接。
我已经reverseLL单独测试过它并且它可以工作,但是当它作为 isPalindrome 方法的一部分应用时。知道我可能缺少什么吗?
动漫人物
qq_笑_17
相关分类