File tree Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Expand file tree Collapse file tree 1 file changed +71
-0
lines changed Original file line number Diff line number Diff line change @@ -144,6 +144,75 @@ public:
144
144
## Java
145
145
146
146
```java
147
+ // 方法一,使用数组
148
+ class Solution {
149
+ public boolean isPalindrome(ListNode head) {
150
+ int len = 0;
151
+ // 统计链表长度
152
+ ListNode cur = head;
153
+ while (cur != null) {
154
+ len++;
155
+ cur = cur.next;
156
+ }
157
+ cur = head;
158
+ int[] res = new int[len];
159
+ // 将元素加到数组之中
160
+ for (int i = 0; i < res.length; i++){
161
+ res[i] = cur.val;
162
+ cur = cur.next;
163
+ }
164
+ // 比较回文
165
+ for (int i = 0, j = len - 1; i < j; i++, j--){
166
+ if (res[i] != res[j]){
167
+ return false;
168
+ }
169
+ }
170
+ return true;
171
+ }
172
+ }
173
+
174
+ // 方法二,快慢指针
175
+ class Solution {
176
+ public boolean isPalindrome(ListNode head) {
177
+ // 如果为空或者仅有一个节点,返回true
178
+ if (head == null && head.next == null) return true;
179
+ ListNode slow = head;
180
+ ListNode fast = head;
181
+ ListNode pre = head;
182
+ while (fast != null && fast.next != null){
183
+ pre = slow; // 记录slow的前一个结点
184
+ slow = slow.next;
185
+ fast = fast.next.next;
186
+ }
187
+ pre.next = null; // 分割两个链表
188
+
189
+ // 前半部分
190
+ ListNode cur1 = head;
191
+ // 后半部分。这里使用了反转链表
192
+ ListNode cur2 = reverseList(slow);
193
+
194
+ while (cur1 != null){
195
+ if (cur1.val != cur2.val) return false;
196
+
197
+ // 注意要移动两个结点
198
+ cur1 = cur1.next;
199
+ cur2 = cur2.next;
200
+ }
201
+ return true;
202
+ }
203
+ ListNode reverseList(ListNode head){
204
+ // 反转链表
205
+ ListNode tmp = null;
206
+ ListNode pre = null;
207
+ while (head != null){
208
+ tmp = head.next;
209
+ head.next = pre;
210
+ pre = head;
211
+ head = tmp;
212
+ }
213
+ return pre;
214
+ }
215
+ }
147
216
```
148
217
149
218
## Python
@@ -209,11 +278,13 @@ class Solution:
209
278
## Go
210
279
211
280
``` go
281
+
212
282
```
213
283
214
284
## JavaScript
215
285
216
286
``` js
287
+
217
288
```
218
289
219
290
You can’t perform that action at this time.
0 commit comments