问题:对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法(不产生新的链表),判断其是否为回文结构,bollean类型返回true,false.。回文结构:例如1->2->2->1
方法:首先要判断链表为空以及只有一个结点的情况。接下来
1.找中间结点(利用快慢指针,slow走一步,fast走两步)详见JAVA——快慢指针解决链表相关问题(一)
2.进行翻转,把中点以后的链表进行翻转,要有三个变量进行转换。
3.两头往中间走,在head和slow不相等的情况下(未走到中间的情况下),判断head和slow的值是否相等,偶数走到head.next=slow处,返回true;奇数走到head和slow相等处,返回true。
代码:
public boolean chkPalindrome(ListNode head) {
if(head==null){
return true;
}if(head.next==null){
return true;
}
//1.找中间结点
ListNode slow=head;
ListNode fast=head;
while(fast!=null && fast.next!=null){//先要判断fast再判断fast.next
slow=slow.next;
fast=fast.next.next;
}
//此时slow指向的结点就是中间结点。
//2.进行翻转
ListNode cur=slow.next;
while(cur!=null){
ListNode curNext=cur.next;//不可以在循环外,若cur为null,则curNext会产生空指针异常
cur.next=slow;
slow=cur;
cur=curNext;
}
//此时已经翻转完毕 slow指向的地方就是最后一个结点
while(slow!=head){
if(slow.val!=head.val){
return false;
}
if(head.next==slow){
return true;
}
head=head.next;
slow=slow.next;
}
return true;
}