Skip to content

Commit 8a34937

Browse files
Create 234. 回文链表.md
1 parent 48bf982 commit 8a34937

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Linked List/234. 回文链表.md

+82
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#### 234. 回文链表
2+
3+
难度:简单
4+
5+
---
6+
7+
给你一个单链表的头节点 `head` ,请你判断该链表是否为
8+
9+
回文链表
10+
11+
。如果是,返回 `true` ;否则,返回 `false`
12+
13+
**示例 1:**
14+
15+
![](https://assets.leetcode.com/uploads/2021/03/03/pal1linked-list.jpg)
16+
```
17+
输入:head = [1,2,2,1]
18+
输出:true
19+
```
20+
21+
**示例 2:**
22+
23+
![](https://assets.leetcode.com/uploads/2021/03/03/pal2linked-list.jpg)
24+
```
25+
输入:head = [1,2]
26+
输出:false
27+
```
28+
29+
**提示:**
30+
31+
* 链表中节点数目在范围`[1, 10^5]`
32+
* `0 <= Node.val <= 9`
33+
34+
**进阶:** 你能否用 `O(n)` 时间复杂度和 `O(1)` 空间复杂度解决此题?
35+
36+
---
37+
38+
进阶,用快慢指针和反转链表的方式:
39+
40+
首先用快慢指针找到链表中点,接着将中点后的节点反转,得到新的节点后与 `head` 节点逐个比较值。
41+
42+
```Go
43+
/**
44+
* Definition for singly-linked list.
45+
* type ListNode struct {
46+
* Val int
47+
* Next *ListNode
48+
* }
49+
*/
50+
func isPalindrome(head *ListNode) bool {
51+
mid := endOfFirstHalf(head)
52+
end := reverse(mid.Next)
53+
for end != nil {
54+
if head.Val != end.Val {
55+
return false
56+
}
57+
end = end.Next
58+
head = head.Next
59+
}
60+
return true
61+
}
62+
63+
func reverse(cur *ListNode) *ListNode {
64+
var pre *ListNode
65+
for cur != nil {
66+
next := cur.Next
67+
cur.Next = pre
68+
pre = cur
69+
cur = next
70+
}
71+
return pre
72+
}
73+
74+
func endOfFirstHalf(head *ListNode) *ListNode {
75+
slow, fast := head, head
76+
for fast.Next != nil && fast.Next.Next != nil {
77+
slow = slow.Next
78+
fast = fast.Next.Next
79+
}
80+
return slow
81+
}
82+
```

0 commit comments

Comments
 (0)