Created
March 10, 2021 10:16
-
-
Save MohammedALREAI/592c59b61c3aedfbc1bb0be783c163df to your computer and use it in GitHub Desktop.
234. Palindrome Linked List leetcode
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. | |
* class ListNode { | |
* val: number | |
* next: ListNode | null | |
* constructor(val?: number, next?: ListNode | null) { | |
* this.val = (val===undefined ? 0 : val) | |
* this.next = (next===undefined ? null : next) | |
* } | |
* } | |
*/ | |
function isPalindrome(head: ListNode | null): boolean { | |
//we nned to rach to mid item and compare lef and right | |
let slow=head; | |
let fast=head; | |
while(slow && fast && fast.next){ | |
// push the | |
slow=slow.next; | |
fast=fast.next.next | |
} | |
fast=head; | |
slow=reverse(slow); | |
while(slow){ | |
if(slow.val!==fast.val) return false | |
slow=slow.next | |
fast=fast.next | |
} | |
return true | |
}; | |
function reverse(head: ListNode | null):ListNode | null{ | |
let pre=null; | |
while(head){ | |
let temp=head.next; | |
head.next=pre; | |
pre=head | |
head=temp | |
} | |
return pre | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment