參考博客:https://blog.csdn.net/whm114336793/article/details/79996943
思想:使用快慢指針,當快指針走的終點的時候,慢指針在中間的位置,把中間到最後的位置開始倒序鏈表。其中要分奇偶考慮,如果是奇數,slow = slow—>next。然後將前半部分和後半部分分別從兩頭開始比較元素是否相等。此算法時間複雜度O(N),空間複雜度O(1)。
代碼如下:
'''
參考的博客:https://blog.csdn.net/whm114336793/article/details/79996943
'''
class Node(object):
def __init__(self, data, next=None):
"Instantiates a Node with a default next of None."
self.data = data
self.next = next
# 得到的是逆序的:不過此問題中沒有影響
def getLinkedList(str):
head = None
# Add nodes to the linked structure
for item in str:
# print(item)
head = Node(item, head)
# print("head.data:", head.data)
# print("before:", head.next)
return head
def isPalindrome(node, isEven):
if (node == None):
return True
elif (node.next == None):
return True
else:
fast = node
slow = node
# 偶數
while ((fast.next.next != None) & (isEven == True)):
# print("fast.data", fast.data)
# print("slow.data", slow.data)
fast = fast.next.next
slow = slow.next
# 奇數
while ((fast.next != None) & (isEven == False)):
# print("fast.data", fast.data)
# print("slow.data", slow.data)
fast = fast.next.next
slow = slow.next
# 如果節點個數是奇數,跳過中間的節點
if (fast != None):
slow = slow.next
print("slow.data:", slow.data)
# 記錄中間節點的下一個節點
high = slow.next
# 中間位置上的節點的下一個節點指向null
slow.next = None
temp = None
# 跟頭插法還不太一樣
while (high != None):
temp = high.next
high.next = slow
slow = high
high = temp
# 記錄開始的頭節點
temp = node
# 記錄後半部分的頭節點
high = slow
flag = True
while ((temp != None) & (high != None)):
if (temp.data != high.data):
flag = False
break
temp = temp.next
high = high.next
return flag
def main():
if __name__ == '__main__':
# 判斷是否爲偶數
isEven = False
str = "abcdeffdcba"
length = len(str)
if (length % 2) == 0:
isEven = True
else:
isEven = False
node = getLinkedList(str)
print("isEven:", isEven)
flag = isPalindrome(node, isEven)
print("result:", flag)
main()
注意:分奇偶討論還有一個地方需要考慮,就是如果參考博客中的寫法:
while ((fast.next != None) & (fast.next.next != None))
這種情況對於包含偶數個元素的字符串沒有問題,但是當字符串包含偶數個元素時while條件所在行就會報錯如下:
原因如下:
上面的藍色箭頭代表fast節點,下面的紅色箭頭代表slow節點,當fast指向元素c所在的節點時,fast.next.next 指向元素a所在的節點,滿足while條件,故執行下面的語句:fast = fast.next.next slow = slow.next 此時fast指向元素a所在的節點,再去判斷是否滿足while循環,但是此時a—>next = null,所以a—>next沒有next屬性了,就會報錯!!!!