# -*- coding:utf-8 -*-
'''題目描述
請編寫乙個函式,檢查鍊錶是否為回文。
給定乙個鍊錶listnode* phead,請返回乙個bool,代表鍊錶是否為回文。
測試樣例:
返回:true
返回:false
@author chimuuu
'''class listnode:
def __init__(self, x):
self.val = x
self.next = none
class palindrome:
def ispalindrome(self, phead):
# write code here
if phead == none or phead.next == none:
return true
pslow = phead
pfast = phead
stack = [pslow.val]
# 查詢鍊錶中心
while true:
# 奇數鏈,比較從後半部分第乙個開始
if not pfast.next:
mid = pslow
break
# 偶數鏈,比較從後半部分第乙個開始
elif pfast and not pfast.next.next:
mid = pslow.next
break
pslow = pslow.next
pfast = pfast.next.next
# 回文對比
print stack
while stack and mid.next:
tmp = stack.pop()
if mid.val != tmp:
return false
print mid.val, tmp
mid = mid.next
return true
node1 = listnode(1)
node2 = listnode(2)
node3 = listnode(3)
# node4 = listnode(3)
node5 = listnode(2)
node6 = listnode(1)
node1.next = node2
node2.next = node3
node3.next = node5
# node4.next = node5
node5.next = node6
s = palindrome()
p = s.ispalindrome(node1)
print(p)
檢查鍊錶是否為回文
請編寫乙個函式,檢查鍊錶是否為回文。給定乙個鍊錶listnode phead,請返回乙個bool,代表鍊錶是否為回文。演算法實現如下 public class listnode class result public class palindrome result result ispalindro...
面試13之檢查鍊錶是否為回文
題目描述 請編寫乙個函式,檢查鍊錶是否為回文。給定乙個鍊錶listnode phead,請返回乙個bool,代表鍊錶是否為回文。測試樣例 返回 true 返回 false includeusing namespace std includestruct listnode 方式一 用乙個輔助棧,時間複...
Python判斷是否為回文鍊錶
突然發現python語法的優美和簡潔,清爽,不拖泥帶水。龜叔 guido van rossum 就說 除了不能生孩子,python真的能幹很多事。definition for singly linked list.如果位元組面試 時間複雜度o n 空間複雜度o 1 class listnode de...