Skip to content

Commit

Permalink
finish 0234
Browse files Browse the repository at this point in the history
  • Loading branch information
benben6515 committed May 8, 2022
1 parent d3a8403 commit db8a825
Show file tree
Hide file tree
Showing 2 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ since 2021.10.10 / Benben
- 0144.Binary Tree PreOrder Traversal
- 0206.Reverse Linked List
- 0226.Invert Binary Tree
- 0234.Palindrome Linked List
- 0509.Fibonacci Number
- 0543.Diameter of Binary Tree
- 0704.Binary Search
Expand Down
71 changes: 71 additions & 0 deletions leetcode-easy/0234-palindrome-linked-list.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
/**
* 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) {
/**
* solution 01
*/

// let left = head
// let counter = 0
//
// const traverse = (right) => {
// if (right === null) return true
// let res = traverse(right.next)
//
// res = res && (left.val === right.val)
// left = left.next
// return res
// }
//
// return traverse(head)

/**
* solution 02
*/

const reverse = (head) => {
let cur = head
let prev = null
let next = null
while (cur !== null) {
next = cur.next
cur.next = prev
prev = cur
cur = next
}
return prev
}

let slow = head
let fast = head

while (fast !== null && fast.next !== null) {
slow = slow.next
fast = fast.next.next
}

if (fast !== null) slow = slow.next

let left = head
let right = reverse(slow)

while (right !== null) {
if (left.val !== right.val) return false
left = left.next
right = right.next
}
return true
};

// 2022/05/08 done.
// Runtime: 203 ms, faster than 50.96% of JavaScript online submissions for Palindrome Linked List.
// Memory Usage: 68.7 MB, less than 89.18% of JavaScript online submissions for Palindrome Linked List.

0 comments on commit db8a825

Please sign in to comment.