234 回文鍊錶

2021-10-22 07:12:10 字數 3144 閱讀 9926

請判斷乙個鍊錶是否為回文鍊錶。

示例 1:

輸入: 1->2

輸出: false

示例 2:

輸入: 1->2->2->1

輸出: true

高階:

你能否用 o(n) 時間複雜度和 o(1) 空間複雜度解決此題?

思路1: 借助棧依次壓入每個節點,然後判斷棧頂和當前鍊錶節點的每個值。

# definition for singly-linked list.

# class listnode:

# def __init__(self, val=0, next=none):

# self.val = val

# self.next = next

class

solution

:def

ispalindrome

(self, head: listnode)

->

bool

: stack =

cur = head

while cur is

notnone

: cur = cur.

next

while head is

notnone

:if head.val != stack.pop(

).val:

return

false

head = head.

next

return

true

思路2: 利用棧,但是只存入一半的資料結構。

# definition for singly-linked list.

# class listnode:

# def __init__(self, val=0, next=none):

# self.val = val

# self.next = next

class

solution

:def

ispalindrome

(self, head: listnode)

->

bool

: stack =

cur = head

right = head.

next

while cur.

next

isnot

none

and cur.

next

.next

isnot

none

: right = right.

next

cur = cur.

next

.next

while right is

notnone

: right = right.

next

while stack:

if head.val != stack.pop(

).val:

return

false

head = head.

next

return

true

思路3: 原鍊錶基礎上後半部分進行反轉,然後再判斷,最後還原。

# definition for singly-linked list.

# class listnode:

# def __init__(self, val=0, next=none):

# self.val = val

# self.next = next

class

solution

:def

ispalindrome

(self, head: listnode)

->

bool

:if head is

none

or head.

next

isnone

:return

true

n1 = head

n2 = head

while n2.

next

isnot

none

and n2.

next

.next

isnot

none

: n1 = n1.

next

n2 = n2.

next

.next

n2 = n1.

next

n1.next

=none

n3 =

none

# 反轉右半部分鍊錶

while n2 is

notnone

: n3 = n2.

next

n2.next

= n1

n1 = n2

n2 = n3

# 進行判斷是否為回文結構

n3 = n1 #儲存最後1個節點

n2 = head

res =

true

while n1 is

notnone

and n2 is

notnone

:if n1.val != n2.val:

res =

false

break

n1 = n1.

next

n2 = n2.

next

# 將鍊錶復原

n1 = n3.

next

n3.next

=none

while n1 is

notnone

: n2 = n1.

next

n1.next

= n3

n3 = n1

n1 = n2

return res

234 回文鍊錶

請判斷乙個鍊錶是否為回文鍊錶。示例 1 輸入 1 2輸出 false示例 2 輸入 1 2 2 1輸出 true首先建立兩個指標指向鍊錶,然後使其中乙個指標指向鍊錶中間,這裡可以使用另乙個指標快速移動,當另乙個指標移動速度是前一根指標的一倍時,就可以使slow指標到一半,而fast指標遍歷完了。使用...

234 回文鍊錶

請判斷乙個鍊錶是否為回文鍊錶。示例 1 輸入 1 2 輸出 false 示例 2 輸入 1 2 2 1 輸出 true 高階 你能否用 o n 時間複雜度和 o 1 空間複雜度解決此題?正確思路是1.先找到鍊錶的中點 通過快慢雙指標,快指標一次移動兩個單位,慢指標一次移動乙個單位,當快指標頂到頭的時...

234回文鍊錶

題目描述 請判斷乙個鍊錶是否為回文鍊錶。示例 1 輸入 1 2 輸出 false 示例 2 輸入 1 2 2 1 輸出 true 題解思路 首先反思一下,我這一題的第一想法是將整個鍊錶反轉,然後和原鍊錶同步遍歷,全部相同便是回文鍊錶,但是發現,你在反轉鍊錶的時候,原鍊錶被破壞了,所以第一次失敗。然後...