2.7

題目描述
請編寫一個(gè)函數(shù),檢查鏈表是否為回文。
給定一個(gè)鏈表ListNode* pHead,請返回一個(gè)bool,代表鏈表是否為回文。
測試樣例:
{1,2,3,2,1}
返回:true
{1,2,3,2,3}
返回:false

package Chapter2;

public class Palindrome {
//    題目描述
//    請編寫一個(gè)函數(shù),檢查鏈表是否為回文。
//    給定一個(gè)鏈表ListNode* pHead,請返回一個(gè)bool,代表鏈表是否為回文。
//    測試樣例:
//    {1,2,3,2,1}
//    返回:true
//    {1,2,3,2,3}
//    返回:false
public boolean isPalindrome(ListNode pHead) {
    if(pHead == null){
        return true;
    }
    int length=0;
    ListNode pHead1=pHead;
    while(pHead1 != null){
        length++;
        pHead1=pHead1.next;
    }
    if(length == 1){
        return true;
    }
    ListNode pHead2=pHead;
    ListNode pHeadBeforeBegin=null;
    ListNode pHeadBeforeEnd=null;
    for(int i=0;i<length/2;i++){
            if(pHeadBeforeBegin == null){
                pHeadBeforeBegin=new ListNode(pHead2.val);
                pHeadBeforeEnd=pHeadBeforeBegin;
            }else{
                ListNode tmp=new ListNode(pHead2.val);
                pHeadBeforeEnd.next=tmp;
                pHeadBeforeEnd=pHeadBeforeEnd.next;
            }
        pHead2=pHead2.next;
    }
    if(length%2 == 1){
        pHead2=pHead2.next;
    }
    ListNode newBegin=new ListNode(-1);
    ListNode newEnd=null;
    while(pHead2 != null){
        ListNode tmp=new ListNode(pHead2.val);
        tmp.next=newEnd;
        newEnd=tmp;
        newBegin.next=tmp;
        pHead2=pHead2.next;
    }
    newBegin=newBegin.next;
    while(newBegin != null){
        if(newBegin.val != pHeadBeforeBegin.val){
            return false;
        }
        newBegin=newBegin.next;
        pHeadBeforeBegin=pHeadBeforeBegin.next;
    }
    return true;
    // write code here
}
    public static void main(String[] args){
        ListNode myListNode=ListNodeOperation.createListNode();
        System.out.println(new Palindrome().isPalindrome(myListNode));

    }

}

以下思路非常不錯(cuò),具體代碼就不貼了


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容