Skip to content

Instantly share code, notes, and snippets.

@jchudzynski
Created April 30, 2015 21:22
Show Gist options
  • Save jchudzynski/764b5b561cff333f1e2f to your computer and use it in GitHub Desktop.
Save jchudzynski/764b5b561cff333f1e2f to your computer and use it in GitHub Desktop.
LeetCode Remove nth element from the end from linked list in Swift.
class ListNode{
var val:Int?
var next:ListNode?
init(){}
init(x:Int){
self.val = x
}
}
func createLinkedList()->ListNode {
var l1 = ListNode(x:1)
var l2 = ListNode(x:2)
var l3 = ListNode(x:3)
var l4 = ListNode(x:4)
var l5 = ListNode(x:5)
// l1.next = l2
// l2.next = l3
// l3.next = l4
// l4.next = l5
return l1
}
func removeNTH(head:ListNode, n:Int)->ListNode?{
var firstNode:ListNode! = head
var secondNode:ListNode! = head
//increment the first node to N position from the beginning
for var i = 0; i < n+1; i++ {
firstNode = firstNode.next
}
//checking for boundary problem
if firstNode == nil {
return head.next
}
//now continune node by node checking if we didn't reach the end
while firstNode != nil{
firstNode = firstNode.next
secondNode = secondNode.next
}
secondNode.next = secondNode.next?.next
return head
}
func printKeys(list:ListNode){
var i = 0
var current:ListNode! = list
while ( current != nil)
{
i++;
println(current.val)
current = current.next
if (i > 10) { break }
}
}
var node = removeNTH(createLinkedList(), 1)
printKeys(node!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment