-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path234.回文链表.go
49 lines (46 loc) · 825 Bytes
/
234.回文链表.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
* @lc app=leetcode.cn id=234 lang=golang
*
* [234] 回文链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func isPalindrome(head *ListNode) bool {
if head == nil {
return true
}
slow := head
fast := head.Next
for fast!= nil && fast.Next !=nil {
slow = slow.Next
fast = fast.Next.Next
}
secondHalf := slow.Next
slow.Next = nil
reverser := reverse(secondHalf)
for head != nil && reverser != nil {
if head.Val != reverser.Val {
return false
}
head = head.Next
reverser = reverser.Next
}
return true
}
func reverse(head *ListNode) *ListNode {
var prevNode *ListNode
for head !=nil {
tmp := head.Next
head.Next = prevNode
prevNode = head
head = tmp
}
return prevNode
}
// @lc code=end