Created
April 30, 2015 21:22
-
-
Save jchudzynski/764b5b561cff333f1e2f to your computer and use it in GitHub Desktop.
LeetCode Remove nth element from the end from linked list in Swift.
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
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