Skip to content

Instantly share code, notes, and snippets.

@t0rn
Created October 25, 2018 16:26
Show Gist options
  • Save t0rn/de7a1e74d83830a1dfc7e350da0ea6ef to your computer and use it in GitHub Desktop.
Save t0rn/de7a1e74d83830a1dfc7e350da0ea6ef to your computer and use it in GitHub Desktop.
Loop in Linked List With Swift
import Foundation
class LinkedList<T> {
class Node<T> {
var value: T
var next: Node?
init (value: T){
self.value = value
}
}
private var head: LinkedList.Node<T>?
var isEmpty: Bool {
return head == nil
}
var first: LinkedList.Node<T>? {
return head
}
var last: LinkedList.Node<T>? {
guard var node = head else {
return nil
}
while let next = node.next {
node = next
}
return node
}
func append(value:T) {
let newNode = Node(value: value)
if let lastNode = last {
lastNode.next = newNode
} else {
head = newNode
}
}
}
extension LinkedList where T: Equatable {
var isLoopedList: Bool {
guard var node = head else {return false}
var xs = [T](arrayLiteral: node.value)
while let next = node.next {
if xs.contains(next.value) {
return true
}
xs.append(next.value)
node = next
}
return false
}
}
//TODO: add Floyd's cycle detection algorithm
//test
let list = LinkedList<String>()
let string1 = "Hello"
let string2 = "World"
list.append(value: string1)
list.append(value: string2)
list.isLoopedList
list.append(value: string1)
list.isLoopedList
list.append(value: string2)
list.isLoopedList
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment