Tuesday, August 25, 2015

Leetcode 203. Remove Linked List Elements

https://leetcode.com/problems/remove-linked-list-elements/

Solution:
# T:O(n) S:O(1)
class Solution:
    # @param {ListNode} head
    # @param {integer} val
    # @return {ListNode}
    def removeElements(self, head, val):
        dummy = ListNode(float("-inf"))
        dummy.next = head
        prev, curr = dummy, dummy.next
        
        while curr:
            if curr.val == val:
                prev.next = curr.next
            else:
                prev = curr
            
            curr = curr.next
        
        return dummy.next
Run Time: 128 ms

No comments:

Post a Comment