-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpalindromeLinkedList.js
96 lines (77 loc) · 1.98 KB
/
palindromeLinkedList.js
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
234. Palindrome Linked List
Given the head of a singly linked list, return true if it is a palindrome or false otherwise.
Example 1:
Input: head = [1,2,2,1]
Output: true
Example 2:
Input: head = [1,2]
Output: false
*/
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {boolean}
*/
// var isPalindrome = function (head) {
// // Get midddle of the list by using a fast and slow pointer
// let slow = head
// let fast = head
// while (fast && fast.next) {
// slow = slow.next
// fast = fast.next.next
// }
// // Reverse the end of the list
// let reversed = null
// let next = null
// let cur = slow
// while (cur) {
// next = cur.next;
// cur.next = reversed;
// reversed = cur;
// cur = next;
// }
// // Then traverse both lists to compare values returning false if any of them aren't equal
// console.log(head) // for example [1,2,2,1] // [1,2,2]
// console.log(reversed) // [1,2]
// while (reversed) {
// if (reversed.val !== head.val) return false
// reversed = reversed.next
// head = head.next
// }
// return true
// };
var isPalindrome = function (head) {
let slow = head;
let fast = head;
let prev = null;
let next = null;
// Reversed the first half of list
while (fast !== null && fast.next !== null) {
fast = fast.next.next;
next = slow.next;
slow.next = prev;
prev = slow;
slow = next;
}
if (fast !== null) {
slow = slow.next;
}
console.log(slow) // [2, 1]
console.log(prev) // [2, 1]
// comapring two halves
while (slow !== null) {
if (slow.val !== prev.val) {
return false;
}
slow = slow.next;
prev = prev.next;
}
return true;
};