Palindrome Linked List

Solution in Go

func isPalindrome(head *ListNode) bool {
    slow, fast := head, head

    for fast != nil && fast.Next != nil {
        slow = slow.Next
        fast = fast.Next.Next
    }

    // Odd numbers in the list
    if fast != nil {
        slow = slow.Next
    }

    list2 := reverseList(slow)

    temp1 := head
    temp2 := list2

    for temp2 != nil {
        if temp1.Val != temp2.Val {
            return false
        }

        temp1 = temp1.Next
        temp2 = temp2.Next
    }

    return true
}

func reverseList(head *ListNode) *ListNode {
    var prev *ListNode
    var curr *ListNode = head

    for curr != nil {
        next := curr.Next
        curr.Next = prev
        prev = curr
        curr = next
    }

    return prev
}
Subscribe via email

Get notified once/twice per month when new articles are published.

Copyright © 2022 - 2024 TheDeveloperCafe.
The Go gopher was designed by Renee French.