203.203. Remove Linked List Elements | Link
方法一:常规方法(分别处理头节点和中间节点)
# 方法1:不适用虚拟头节点;需要分head和非head两种情况处理
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
while head != None and head.val == val:
head = head.next
cur = head
while cur != None and cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return head
方法二:Dummy Head
# 方法二 虚拟头节点 dummyHead
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummyHead = ListNode(next=head)
cur = dummyHead
while cur.next != None:
if cur.next.val == val:
cur.next = cur.next.next
else:
cur = cur.next
return dummyHead.next
- 如何选取cur(操作结点)?
由于(单)ListNode的不可逆性,因此cur的选择原则是,所有你操作的Node中最靠左的。 - 由于如果指针是None,我们引用时会报错,因此我们要提前排除指针为None的情况。
哪些情况需要排除?只要你要用到的Node,就要判定其不是None。
例如第一个while条件,我们仅对head操作,因此条件就是head!=None;
第二个while条件,我们对cur和cur.next操作,因此条件就是 两者均 !=None;