Skip to content

Commit

Permalink
[LinkedList] Optimize solution to Remove LinkedList Element
Browse files Browse the repository at this point in the history
  • Loading branch information
Yi Gu committed Dec 24, 2016
1 parent f197a7d commit 69496a6
Showing 1 changed file with 6 additions and 12 deletions.
18 changes: 6 additions & 12 deletions LinkedList/RemoveLinkedListElements.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,18 @@
*/

class RemoveLinkedListElements {
func removeElements(head: ListNode?, _ val: Int) -> ListNode? {
func removeElements(_ head: ListNode?, _ val: Int) -> ListNode? {
let dummy = ListNode(0)
dummy.next = head
var node = dummy

var prev = dummy
var curr = head

while curr != nil {
if curr!.val == val {
curr = curr!.next
while node.next != nil {
if node.next!.val == val {
node.next = node.next!.next
} else {
prev.next = curr
prev = curr!
curr = curr!.next
node = node.next!
}
}
// remember to handle the last one
prev.next = nil

return dummy.next
}
Expand Down

0 comments on commit 69496a6

Please sign in to comment.