Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit fd1c44a

Browse files
Merge pull request #7 from janeyziqinglin/janeyziqinglin-patch-7
Update 0234.回文链表 python版本
2 parents a62775e + c990026 commit fd1c44a

File tree

1 file changed

+28
-46
lines changed

1 file changed

+28
-46
lines changed

‎problems/0234.回文链表.md‎

Lines changed: 28 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -218,59 +218,41 @@ class Solution {
218218
```python
219219
#数组模拟
220220
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]:
239229
return False
240-
i +=1
241-
j -=1
242-
return True
243-
230+
l+=1
231+
r-=1
232+
return True
233+
244234
#反转后半部分链表
245235
class Solution:
246-
def isPalindrome(self, head: ListNode) -> bool:
247-
if head ==Noneor head.next ==None:
248-
returnTrue
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
250240
while fast and fast.next:
251-
pre = slow
252-
slow = slow.next
253241
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:
260252
return False
261-
cur1 = cur1.next
262-
cur2 = cur2.next
253+
node = node.next
254+
head = head.next
263255
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
274256
```
275257

276258
## Go

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /