链表 回文结构

对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。

给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。

import java.util.*;
 
/*
public class ListNode {
    int val;
    ListNode next = null;
 
    ListNode(int val) {
        this.val = val;
    }
}*/
public class PalindromeList {
    public ListNode getMid(ListNode head){
    ListNode fast=head;
    ListNode low=head;
    while(fast!=null){
        fast=fast.next;
        if (fast==null){ 
            break;
            }
        low=low.next;
        fast=fast.next;
    }
    return low;
}
     
public ListNode reverse(ListNode head){
    if(head==null) return null;
    ListNode pre=null;
    ListNode next=null;
    while(head!=null){
        next=head.next;
        head.next=pre;
        pre=head;
        head=next;
    }
    return pre;
}
    public boolean chkPalindrome(ListNode A) {
        // write code here
        ListNode mid=getMid(A);
        ListNode h2=reverse(mid);
        ListNode n1=A;
        ListNode n2=h2;
        while(n1!=null&&n2!=null){
            if(n1.val!=n2.val){
                return false;
            }
            n1=n1.next;
            n2=n2.next;
        }
        return true;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值