203. 移除链表元素

随机pick的一道简单题
移除链表中的特定元素

我自己提交的代码:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
	def removeElements(self, head: ListNode, val: int) -> ListNode:
		***# 最开始忘记了head为空的情况***
		if head == None:
			return None
		while head.val == val:
			head = head.next
			if head == None:
				return None
		temp = head
		tail = head
		while tail != None:
			if tail.val != val:
				temp = tail
				tail = tail.next
			else:
				tail = tail.next
				temp.next = tail
		return head

然后提交通过以后
看题解才想起以前学数据结构好像有一个方法
是在head前面加一个虚拟的virtual_head,然后最后返回virtual_head.next
这样可以减去一开始对于head的处理
Mark一个范例:

203. 移除链表元素