#! 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 = None
class 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
python---删除链表中的元素
最新推荐文章于 2022-08-10 23:06:35 发布