Skip to content

Commit 976379c

Browse files
committed
0234-回文链表Java实现
1 parent da87ff9 commit 976379c

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

problems/0234.回文链表.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,75 @@ public:
144144
## Java
145145
146146
```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+
}
147216
```
148217

149218
## Python
@@ -209,11 +278,13 @@ class Solution:
209278
## Go
210279

211280
```go
281+
212282
```
213283

214284
## JavaScript
215285

216286
```js
287+
217288
```
218289

219290

0 commit comments

Comments
 (0)