剑指Offer027-回文链表

题目描述:

在这里插入图片描述如果链表为空返回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;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值