Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created July 7, 2019 22:00
Show Gist options
  • Select an option

  • Save davidinga/b0e4722457d6afcc73e26125171aa014 to your computer and use it in GitHub Desktop.

Select an option

Save davidinga/b0e4722457d6afcc73e26125171aa014 to your computer and use it in GitHub Desktop.
Determines if a linked list is a palindrome. Both solutions work for a singly or doubly linked list.
func isPalindrome(_ list: DoublyLinkedList<String>) -> Bool {
// Simple solution. Iterate over linked list and store as string.
// Uses linear space and time.
// Then compare string to a reversed string.
// If equal, then we have a palindrome.
var node = list.first
var string = ""
while node != nil {
string += String(node!.element)
node = node!.next
}
return string == String(string.reversed())
}
func isPalindrome(_ list: SinglyLinkedList<String>) -> Bool {
// Recursive solution. Uses constant space and linear time.
// Checks first and last elements in linked list.
// Removes elements from front and back until there
// is one element, no elements, or an invalid palindrome is found.
if list.isEmpty || list.first === list.last {
return true
}
if list.first!.element == list.last!.element {
_ = list.remove(node: list.first!)
_ = list.remove(node: list.last!)
return isPalindrome(list)
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment