mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-10 04:06:51 +08:00
Update 0234.回文链表.md
For both solution of python3, there are shorter and more efficient ways to write it. For the #数组模拟, it can be solved more easily by convert the linked list to a list #反转后半部分链表, the original version define to function, isPalindrome, and reverseList. That's too complicated... No need.
This commit is contained in:
@ -218,59 +218,41 @@ class Solution {
|
|||||||
```python
|
```python
|
||||||
#数组模拟
|
#数组模拟
|
||||||
class Solution:
|
class Solution:
|
||||||
def isPalindrome(self, head: ListNode) -> bool:
|
def isPalindrome(self, head: Optional[ListNode]) -> bool:
|
||||||
length = 0
|
list=[]
|
||||||
tmp = head
|
while head:
|
||||||
while tmp: #求链表长度
|
list.append(head.val)
|
||||||
length += 1
|
head=head.next
|
||||||
tmp = tmp.next
|
l,r=0, len(list)-1
|
||||||
|
while l<=r:
|
||||||
result = [0] * length
|
if list[l]!=list[r]:
|
||||||
tmp = head
|
|
||||||
index = 0
|
|
||||||
while tmp: #链表元素加入数组
|
|
||||||
result[index] = tmp.val
|
|
||||||
index += 1
|
|
||||||
tmp = tmp.next
|
|
||||||
|
|
||||||
i, j = 0, length - 1
|
|
||||||
while i < j: # 判断回文
|
|
||||||
if result[i] != result[j]:
|
|
||||||
return False
|
return False
|
||||||
i += 1
|
l+=1
|
||||||
j -= 1
|
r-=1
|
||||||
return True
|
return True
|
||||||
|
|
||||||
#反转后半部分链表
|
#反转后半部分链表
|
||||||
class Solution:
|
class Solution:
|
||||||
def isPalindrome(self, head: ListNode) -> bool:
|
def isPalindrome(self, head: Optional[ListNode]) -> bool:
|
||||||
if head == None or head.next == None:
|
fast = slow = head
|
||||||
return True
|
|
||||||
slow, fast = head, head
|
# find mid point which including (first) mid point into the first half linked list
|
||||||
while fast and fast.next:
|
while fast and fast.next:
|
||||||
pre = slow
|
|
||||||
slow = slow.next
|
|
||||||
fast = fast.next.next
|
fast = fast.next.next
|
||||||
|
slow = slow.next
|
||||||
|
node = None
|
||||||
|
|
||||||
pre.next = None # 分割链表
|
# reverse second half linked list
|
||||||
cur1 = head # 前半部分
|
while slow:
|
||||||
cur2 = self.reverseList(slow) # 反转后半部分,总链表长度如果是奇数,cur2比cur1多一个节点
|
slow.next, slow, node = node, slow.next, slow
|
||||||
while cur1:
|
|
||||||
if cur1.val != cur2.val:
|
# compare reversed and original half; must maintain reversed linked list is shorter than 1st half
|
||||||
|
while node:
|
||||||
|
if node.val != head.val:
|
||||||
return False
|
return False
|
||||||
cur1 = cur1.next
|
node = node.next
|
||||||
cur2 = cur2.next
|
head = head.next
|
||||||
return True
|
return True
|
||||||
|
|
||||||
def reverseList(self, head: ListNode) -> ListNode:
|
|
||||||
cur = head
|
|
||||||
pre = None
|
|
||||||
while(cur!=None):
|
|
||||||
temp = cur.next # 保存一下cur的下一个节点
|
|
||||||
cur.next = pre # 反转
|
|
||||||
pre = cur
|
|
||||||
cur = temp
|
|
||||||
return pre
|
|
||||||
```
|
```
|
||||||
|
|
||||||
## Go
|
## Go
|
||||||
|
Reference in New Issue
Block a user