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
}
    TheDeveloperCafe © 2022-2024