题目描述:
如果链表为空返回false
链表长度为1返回true
思路:
首先这是一个单向链表,无法让它从后往前遍历,其次用 O(n) 时间复杂度和 O(1) 空间复杂度解决。如果想要从头节点向后遍历,从尾节点向前遍历,就需要将中间节点的后续所有节点进行反转。
1:如何确定重点?
定义fast 和 slow 节点,每次fast向后走两步,slow走一步,当fast == null或者fast.next == null,此时slow在中点位置。
2:如何反转?
定义cur,curNext结点。cur初始为slow.next,当cur!=null时,curNext=cur.next,cur.next=slow,slow=cur,cur=curNext。
3:如何比较
使用head向后走,slow向前走,不使用fast是因为fast可能为空,当链表长度为偶数时,fast就会为null。
当链表为奇数,则head == slow就表示相遇,当链表为偶数时,则head.next=slow则表示结束。
head.val==slow.val,head=head.next,slow=slow.next。

代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null){
return false;
}
if(head.next==null){
return true;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null && fast.next!=null){
fast=fast.next.next;
slow=slow.next;
}
ListNode cur=slow.next;
ListNode curNext=null;
while(cur!=null){
curNext=cur.next;
cur.next=slow;
slow=cur;
cur=curNext;
}
while(head!=slow){
if(head.val!=slow.val){
return false;
}
if(head.next==slow){
return true;
}
head=head.next;
slow=slow.next;
}
return true;
}
}
本文解析了如何利用快慢指针技巧判断单链表是否为镜像,通过反转部分节点并对比首尾节点,以O(n)时间复杂度和O(1)空间复杂度完成。关键步骤包括确定链表中点、反转部分节点和最后的比较操作。
323

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



