From 976379c7f28de998cd2a475c4d693978b55ea03a Mon Sep 17 00:00:00 2001 From: bourne-3 <595962708@qq.com> Date: Sun, 29 Aug 2021 20:43:26 +0800 Subject: [PATCH] =?UTF-8?q?0234-=E5=9B=9E=E6=96=87=E9=93=BE=E8=A1=A8Java?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0234.回文链表.md | 71 +++++++++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/problems/0234.回文链表.md b/problems/0234.回文链表.md index 04015a7f..631d2f6b 100644 --- a/problems/0234.回文链表.md +++ b/problems/0234.回文链表.md @@ -144,6 +144,75 @@ public: ## Java ```java +// 方法一,使用数组 +class Solution { + public boolean isPalindrome(ListNode head) { + int len = 0; + // 统计链表长度 + ListNode cur = head; + while (cur != null) { + len++; + cur = cur.next; + } + cur = head; + int[] res = new int[len]; + // 将元素加到数组之中 + for (int i = 0; i < res.length; i++){ + res[i] = cur.val; + cur = cur.next; + } + // 比较回文 + for (int i = 0, j = len - 1; i < j; i++, j--){ + if (res[i] != res[j]){ + return false; + } + } + return true; + } +} + +// 方法二,快慢指针 +class Solution { + public boolean isPalindrome(ListNode head) { + // 如果为空或者仅有一个节点,返回true + if (head == null && head.next == null) return true; + ListNode slow = head; + ListNode fast = head; + ListNode pre = head; + while (fast != null && fast.next != null){ + pre = slow; // 记录slow的前一个结点 + slow = slow.next; + fast = fast.next.next; + } + pre.next = null; // 分割两个链表 + + // 前半部分 + ListNode cur1 = head; + // 后半部分。这里使用了反转链表 + ListNode cur2 = reverseList(slow); + + while (cur1 != null){ + if (cur1.val != cur2.val) return false; + + // 注意要移动两个结点 + cur1 = cur1.next; + cur2 = cur2.next; + } + return true; + } + ListNode reverseList(ListNode head){ + // 反转链表 + ListNode tmp = null; + ListNode pre = null; + while (head != null){ + tmp = head.next; + head.next = pre; + pre = head; + head = tmp; + } + return pre; + } +} ``` ## Python @@ -209,11 +278,13 @@ class Solution: ## Go ```go + ``` ## JavaScript ```js + ```