Created
December 25, 2018 18:42
-
-
Save Ibrahimhass/40d7ebaefb60c66ef86828e2aa1db5a6 to your computer and use it in GitHub Desktop.
This file contains 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
//: Insert Node at Index | |
extension LinkedList { | |
func insertNode(_ node: Node, at position: Int) { | |
guard position > 0 else { | |
return | |
} | |
var counter = 1 | |
var current = head | |
if position > 1 { | |
while current != nil && counter < position { | |
if counter == position - 1 { | |
node.next = current?.next | |
current?.next = node | |
break | |
} | |
current = current?.next | |
counter += 1 | |
} | |
} else if position == 1 { | |
node.next = head | |
head = node | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment