python---删除链表中的元素

来源:互联网 发布:网络虚拟礼物 编辑:程序博客网 时间:2024/06/04 19:53
#! conding:utf-8__author__ = "hotpot"__date__ = "2017/11/13 10:37""""删除链表中等于给定值val的所有节点。给出链表 1->2->3->3->4->5->3, 和 val = 3, 你需要返回删除3之后的链表:1->2->4->5。"""class ListNode:    def __init__(self, x):        self.val = x        self.next = Noneclass Solution:    """    @param: head: a ListNode    @param: val: An integer    @return: a ListNode    """    def removeElements(self, head, val):        # write your code here        tem_head = tem = ListNode(-1)        head_tem = head        # 遍历一遍链表然后发现和val不相等就加入tem后        while head_tem:            if head_tem.val != val:                tem.next = head_tem                tem = tem.next            # 无论相不相等都需要继续遍历,            head_tem = head_tem.next        # 最后结尾的时候一定要加上None,否则tem的下一位很有可能还有其他元素        tem.next = None        return tem_head.next
原创粉丝点击