Published on

Single linked list palindrome

Authors

Problem

Determine whether or not the single linked list is a palindrome.

Solution

In the single linked list case determine palindrome is tricky, because the node only forward and the size is uknown without iterate through the linked list. That means you can't know whether a linked list is palindrome or not without traversing through the linked list.

  • Find the center point of the node list, using double steps (fast var) and reverse the first half of the list.
  • Walk on the second half and walk back in the first to the first difference.
  • Return false if found diff, or true if all items are equal.
solution.go

_41
func solution(l *ListNode) bool {
_41
if l == nil || l.Next == nil {
_41
return true
_41
}
_41
_41
slow := l
_41
fast := l
_41
_41
for fast.Next != nil && fast.Next.Next != nil {
_41
slow = slow.Next
_41
fast = fast.Next.Next
_41
}
_41
_41
reverse := reverseList(slow.Next)
_41
slow.Next = nil
_41
_41
for l != nil && reverse != nil {
_41
if l.Value != reverse.Value {
_41
return false
_41
}
_41
_41
l = l.Next
_41
reverse = reverse.Next
_41
}
_41
_41
return true
_41
}
_41
_41
func reverseList(head *ListNode) *ListNode {
_41
var prev *ListNode
_41
current := head
_41
_41
for current != nil {
_41
next := current.Next
_41
current.Next = prev
_41
prev = current
_41
current = next
_41
}
_41
_41
return prev
_41
}