From a108aadfb58516205cdc2d5b53406efea784e910 Mon Sep 17 00:00:00 2001 From: Steve0x2a Date: Sun, 15 Aug 2021 14:15:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00234=E5=9B=9E=E6=96=87?= =?UTF-8?q?=E9=93=BE=E8=A1=A8=20Python=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0234.回文链表.md | 57 ++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index 6a24b1d0..b3ad899c 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -148,7 +148,62 @@ public: ## Python -```python +```python3 +#数组模拟 +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + length = 0 + tmp = head + while tmp: #求链表长度 + length += 1 + tmp = tmp.next + + result = [0] * length + 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 + i += 1 + j -= 1 + return True + +#反转后半部分链表 +class Solution: + def isPalindrome(self, head: ListNode) -> bool: + if head == None or head.next == None: + return True + slow, fast = head, head + while fast and fast.next: + pre = slow + slow = slow.next + fast = fast.next.next + + pre.next = None # 分割链表 + cur1 = head # 前半部分 + cur2 = self.reverseList(slow) # 反转后半部分,总链表长度如果是奇数,cur2比cur1多一个节点 + while cur1: + if cur1.val != cur2.val: + return False + cur1 = cur1.next + cur2 = cur2.next + 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