[LintCode]Remove Linked List Elements

今天在lintcode网站上做了一道入门级的题目:从一个整数链表中删除指定的数。

题目

Remove all elements from a linked list of integers that have value val.

样例

Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

我的答案[python]:

class ListNode:  
    def __init__(self, x,next=None):
        self.val = x
        self.next = next

    def printMe(self):
        import sys
        sys.stdout.write(str(self.val)+'->')
        next = self.next;
        if next:
            next.printMe()
        else:
            print 'None'

class Solution:  
    # @param head, a ListNode                                                                                                          
    # @param val, an integer                                                                                                           
    # @return a ListNode                                                                                                               
    def removeElements(self, head, val):
        # Write your code here                                                                                                         
        rtn = head
        if head:
            if head.val == val:
                rtn = self.removeElements(head.next,val)
            else:
                head.next = self.removeElements(head.next,val);

        return rtn

if __name__=='__main__':  
    head = ListNode(1,ListNode(2,ListNode(3,ListNode(3,ListNode(4,(ListNode(5,ListNode(3,ListNode(3,None)))))))))
    head.printMe()
#    print head.val                                                                                                                    
    solution = Solution();
    result = solution.removeElements(head,3);
    result.printMe();