@@ -218,59 +218,41 @@ class Solution {
218
218
``` python
219
219
# 数组模拟
220
220
class Solution :
221
- def isPalindrome (self , head : ListNode) -> bool :
222
- length = 0
223
- tmp = head
224
- while tmp: # 求链表长度
225
- length += 1
226
- tmp = tmp.next
227
-
228
- result = [0 ] * length
229
- tmp = head
230
- index = 0
231
- while tmp: # 链表元素加入数组
232
- result[index] = tmp.val
233
- index += 1
234
- tmp = tmp.next
235
-
236
- i, j = 0 , length - 1
237
- while i < j: # 判断回文
238
- if result[i] != result[j]:
221
+ def isPalindrome (self , head : Optional[ListNode]) -> bool :
222
+ list = []
223
+ while head:
224
+ list .append(head.val)
225
+ head= head.next
226
+ l,r= 0 , len (list )- 1
227
+ while l<= r:
228
+ if list[l]!= list[r]:
239
229
return False
240
- i += 1
241
- j -= 1
242
- return True
243
-
230
+ l += 1
231
+ r -= 1
232
+ return True
233
+
244
234
# 反转后半部分链表
245
235
class Solution :
246
- def isPalindrome (self , head : ListNode) -> bool :
247
- if head == None or head.next == None :
248
- return True
249
- slow, fast = head, head
236
+ def isPalindrome (self , head : Optional[ ListNode] ) -> bool :
237
+ fast = slow = head
238
+
239
+ # find mid point which including (first) mid point into the first half linked list
250
240
while fast and fast.next:
251
- pre = slow
252
- slow = slow.next
253
241
fast = fast.next.next
254
-
255
- pre.next = None # 分割链表
256
- cur1 = head # 前半部分
257
- cur2 = self .reverseList(slow) # 反转后半部分,总链表长度如果是奇数,cur2比cur1多一个节点
258
- while cur1:
259
- if cur1.val != cur2.val:
242
+ slow = slow.next
243
+ node = None
244
+
245
+ # reverse second half linked list
246
+ while slow:
247
+ slow.next, slow, node = node, slow.next, slow
248
+
249
+ # compare reversed and original half; must maintain reversed linked list is shorter than 1st half
250
+ while node:
251
+ if node.val != head.val:
260
252
return False
261
- cur1 = cur1 .next
262
- cur2 = cur2 .next
253
+ node = node .next
254
+ head = head .next
263
255
return True
264
-
265
- def reverseList (self , head : ListNode) -> ListNode:
266
- cur = head
267
- pre = None
268
- while (cur!= None ):
269
- temp = cur.next # 保存一下cur的下一个节点
270
- cur.next = pre # 反转
271
- pre = cur
272
- cur = temp
273
- return pre
274
256
```
275
257
276
258
## Go
0 commit comments