Created
April 15, 2022 15:47
-
-
Save Turskyi/b44f279608940019898d22cd523521a6 to your computer and use it in GitHub Desktop.
Given a reference to a linked list, return whether or not it forms a palindrome.
This file contains 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
/* | |
Given a reference to a linked list, return whether or not it forms a palindrome. | |
Ex: Given a reference to the following linked list... | |
head = 1->3->1, return true. | |
* */ | |
fun isPalindrome(head: ListNode?): Boolean { | |
var slow: ListNode? = head | |
var fast: ListNode? = head | |
//find the middle. By the time fast reaches zero, slow will be at half. | |
while (fast?.next != null) { | |
fast = fast.next?.next | |
slow = slow?.next | |
} | |
// reverse second half | |
var prev: ListNode? = null | |
while (slow != null) { | |
val temp = slow.next | |
slow.next = prev | |
prev = slow | |
slow = temp | |
} | |
var left: ListNode? = head | |
var right: ListNode? = prev | |
// compare two linked lists if they are equal | |
while (right != null) { | |
if (left?.`val` != right.`val`) { | |
return false | |
} | |
left = left.next | |
right = right.next | |
} | |
return true | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment