Skip to content

Commit

Permalink
Create 0234-palindrome-linked-list.kt
Browse files Browse the repository at this point in the history
  • Loading branch information
a93a committed Jan 31, 2023
1 parent 7977007 commit 8f4638b
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions kotlin/0234-palindrome-linked-list.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/**
* Example:
* var li = ListNode(5)
* var v = li.`val`
* Definition for singly-linked list.
* class ListNode(var `val`: Int) {
* var next: ListNode? = null
* }
*/
class Solution {
fun isPalindrome(head: ListNode?): Boolean {

var slow = head
var fast = head

// find the middle
while(fast != null && fast.next != null) {
fast = fast?.next?.next
slow = slow?.next
}

//reverse the right part of list (from middle to end)
var prev: ListNode? = null
while(slow != null) {
val temp = slow?.next
slow?.next = prev
prev = slow
slow = temp
}

//traverse both divided parts, left and right portion, to check if palindrome
var left = head
var right = prev
while(right != null) {
if(right?.`val` != left?.`val`) return false
left = left?.next
right = right?.next
}

return true
}
}

0 comments on commit 8f4638b

Please sign in to comment.