题目
题解
快慢指针
快慢指针真是链表题里相当常见的一种解法了,是想到了这种方法的,但是实现有问题(链表反转代码写错了),没有ac,正确解法如下:
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null)
return true;
ListNode fast=head,slow=head;
//slow最后会到后半部分的开头
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
//反转后半部分
ListNode newLastHalf=reverse(slow);
return same(head,newLastHalf);
}
//链表反转
public ListNode reverse(ListNode head){
ListNode p=head;
ListNode pre=null;
while(p!=null){
ListNode r=p.next;
p.next=pre;
pre=p;
p=r;
}
return pre;
}
//判断链表a,b是否相同
public boolean same(ListNode whole,ListNode half){
while(half!=null){
if(whole.val!=half.val)
return false;
whole=whole.next;
half=half.next;
}
return true;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( 1 ) O(1) O(1)
递归
递归判断 head.next 是不是回文链表
class Solution {
private ListNode front=new ListNode();
public boolean isPalindrome(ListNode head) {
front=head;
return judge(head);
}
//递归函数
public boolean judge(ListNode curr){
if(curr==null)
return true;
//递归:相当于先用栈存链表元素,出栈的时候再比较是否是回文,即下一个if
if(!judge(curr.next))
return false;
if(curr.val!=front.val)
return false;
front=front.next;
return true;
}
}
时间复杂度: O ( n ) O(n) O(n)
空间复杂度: O ( n ) O(n) O(n),递归栈的空间