Created
May 24, 2017 09:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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