随机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. 移除链表元素

相关文章:

  • 2022-12-23
  • 2021-06-12
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-09-15
猜你喜欢
  • 2021-05-22
  • 2022-03-05
  • 2022-02-26
  • 2021-08-11
  • 2022-12-23
相关资源
相似解决方案