Created
October 23, 2022 21:17
-
-
Save TobiAlbert/f8e9d24952dcdfbaa7aa118638002cc4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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) { | |
| // 2 -> 1 | |
| let reversedHead = reverseLinkedList(head); | |
| // 1 -> 2 | |
| let currentHead = head; | |
| console.log("about to start comparison"); | |
| console.log(`reversedHead: ${JSON.stringify(reversedHead, null, 4)}`) | |
| console.log(`currentHead: ${JSON.stringify(currentHead, null, 4)}`) | |
| while(reversedHead != null && currentHead != null) { | |
| console.log(`reversed head value: ${reversedHead.val} currentHead: ${currentHead.val}`) | |
| if (reversedHead.val != currentHead.val) { | |
| return false; | |
| } | |
| reversedHead = reversedHead.next; | |
| currentHead = currentHead.next; | |
| } | |
| return true; | |
| }; | |
| var reverseLinkedList = function(head) { | |
| // 1 -> 2 -> 4 -> 5 -> 2 -> 1 | |
| // 1 -> 2 -> 5 -> 4 -> 2 -> 1 | |
| // 1 -> 2 | |
| // 2 -> 1 | |
| let previousHead = null; | |
| let currentHead = head; | |
| while (currentHead != null) { | |
| const node = ListNode(currentHead.val, previousHead); | |
| previousHead = node; | |
| currentHead = currentHead.next; | |
| } | |
| return previousHead; | |
| } | |
| const isPalindromeViaArray = function(head) { | |
| // 1 -> 2 -> 2 -> 1 | |
| const array = []; | |
| let currentHead = head; | |
| // array = [1, 2, 2, 1] | |
| while (currentHead != null) { | |
| const value = currentHead.val; | |
| array.push(value); | |
| currentHead = currentHead.next; | |
| } | |
| let startPointer = 0; | |
| let endPointer = array.length -1; | |
| while(startPointer <= endPointer) { | |
| const startValue = array[startPointer]; | |
| const endValue = array[endPointer]; | |
| if (startValue !== endValue) { | |
| return false; | |
| } | |
| startPointer++; | |
| endPointer--; | |
| } | |
| return true; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment