File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed
Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments