0234回文鏈表_Wise 待更

題目描述

請(qǐng)判斷一個(gè)鏈表是否為回文鏈表。

示例 1:

輸入: 1->2
輸出: false

示例 2:

輸入: 1->2->2->1
輸出: true

進(jìn)階:
你能否用 O(n) 時(shí)間復(fù)雜度和 O(1) 空間復(fù)雜度解決此題?

來(lái)源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/palindrome-linked-list
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。

解題思路

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        if head is None or head.next is None :return True
        # 反轉(zhuǎn)鏈表 同時(shí)計(jì)數(shù)
        pre=ListNode(head.val) 
        print(pre.val)
        pre.next = None
        cur = head.next
        
        long = 1
        # print(cur)
        while cur :
            long += 1
            temp = cur.next
            phead = ListNode(cur.val)
            phead.next = pre
            pre = phead
            cur = temp

        k = (long+1)/2 
        while pre is not None and head is not None and k >= 0:
            print(pre.val,"---",head.val)
            if pre.val != head.val:
                print(pre.val,"---",head.val)
                return False
            pre = pre.next
            head = head.next
            k -= 1
        return True

總結(jié)

鏈表反轉(zhuǎn)

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

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

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