Skip to content

Instantly share code, notes, and snippets.

@Ibrahimhass
Created December 25, 2018 18:42
Show Gist options
  • Save Ibrahimhass/40d7ebaefb60c66ef86828e2aa1db5a6 to your computer and use it in GitHub Desktop.
Save Ibrahimhass/40d7ebaefb60c66ef86828e2aa1db5a6 to your computer and use it in GitHub Desktop.
//: 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