Skip to content

Instantly share code, notes, and snippets.

@MohammedALREAI
Created March 10, 2021 10:16
Show Gist options
  • Save MohammedALREAI/592c59b61c3aedfbc1bb0be783c163df to your computer and use it in GitHub Desktop.
Save MohammedALREAI/592c59b61c3aedfbc1bb0be783c163df to your computer and use it in GitHub Desktop.
234. Palindrome Linked List leetcode
/**
* 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