Skip to content

Commit bb51b04

Browse files
authored
Merge pull request #1929 from josuebrunel/feat/0234-palindrome-linked-list.go
Create 0234-palindrome-linked-list.go
2 parents 66f910e + 2a51c5c commit bb51b04

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Diff for: go/0234-palindrome-linked-list.go

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
Move slow and fast pointer along the list.
3+
Slow pointer nodes are added to reversed list.
4+
When no more fast move is possible, iterate
5+
along slow and back along reversed list while
6+
checking for value equality
7+
8+
Time: O(N)
9+
Space: O(1)
10+
**/
11+
12+
/**
13+
* Definition for singly-linked list.
14+
* type ListNode struct {
15+
* Val int
16+
* Next *ListNode
17+
* }
18+
*/
19+
func isPalindrome(head *ListNode) bool {
20+
slow, fast := head, head
21+
var rev *ListNode
22+
23+
for fast != nil && fast.Next != nil {
24+
fast = fast.Next.Next
25+
next_slow := slow.Next
26+
slow.Next = rev
27+
rev = slow
28+
slow = next_slow
29+
}
30+
31+
// if fast is not null, slow is middle of
32+
// odd length list which is skipped
33+
// if fast is null, slow is first element of
34+
// the 2nd half of even length list
35+
if fast != nil {
36+
slow = slow.Next
37+
}
38+
39+
for slow != nil {
40+
if slow.Val != rev.Val {
41+
return false
42+
}
43+
slow = slow.Next
44+
rev = rev.Next
45+
}
46+
47+
return true
48+
}

0 commit comments

Comments
 (0)