Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save witekbobrowski/db02e200d521aea6fb920be171d40984 to your computer and use it in GitHub Desktop.
Save witekbobrowski/db02e200d521aea6fb920be171d40984 to your computer and use it in GitHub Desktop.
HackerRank - Cracking the Coding Interview - Linked Lists: Detect a Cycle : Swift solution suggestion
import Foundation
class Node {
var data: Int
var next: Node?
init(data: Int) {
self.data = data
}
}
private func hasCycle(head: Node) -> Bool {
var current: Node = head
for _ in 0...100 {
if current.next != nil {
current = current.next!
} else {
return false
}
}
return true
}
// Awkward way to create LinkedList manually with Nodes
var head: Node = Node(data: 1)
var nodeTwo: Node = Node(data: 2)
var nodeThree: Node = Node(data: 3)
head.next = nodeTwo
nodeTwo.next = nodeThree
nodeThree.next = nodeTwo
print(hasCycle(head: head) ? "1" : "0")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment