-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathpalindrome_linked_list.go
75 lines (68 loc) · 1.66 KB
/
palindrome_linked_list.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
package main
// Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// func isPalindrome(head *ListNode) bool {
// return palindrome(head, head)
// }
// func palindrome(head, tail *ListNode) bool {
// if tail.Next != nil {
// if !palindrome(head, tail.Next) { // jump to the last Node
// return false
// }
// }
// if head.Val != tail.Val {
// return false
// }
// if head != tail { // move head to next
// *head = *head.Next
// }
// return true
// }
// func isPalindrome(head *ListNode) bool {
// stack, next := half(head)
// for i := len(stack) - 1; next != nil; i-- {
// if stack[i].Val != next.Val {
// return false
// }
// next = next.Next
// }
// return true
// }
// func half(head *ListNode) ([]*ListNode, *ListNode) {
// stack := make([]*ListNode, 0, 8)
// for fast := head; fast != nil && fast.Next != nil; head = head.Next {
// stack = append(stack, head)
// fast = fast.Next.Next
// if fast == nil {
// break
// }
// }
// return stack, head.Next
// }
func isPalindrome(head *ListNode) bool {
for left, right := partition2(head); left != nil; left, right = left.Next, right.Next {
if left.Val != right.Val {
return false
}
}
return true
}
func partition2(head *ListNode) (left *ListNode, right *ListNode) {
right = head.Next
for fast := head; fast.Next != nil; {
fast = fast.Next.Next
// Critical, reverse operation must happens after fast forwarding.
// Reverse the left half side
left, head.Next = head, left
if fast == nil {
break
}
// Critical, right is faster 1 step than head
// Forward to the front of the right half side
head, right = right, right.Next
}
return
}