LeetCode-203 移除链表元素

题目链接:203. 移除链表元素 - 力扣(LeetCode)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
head1=ListNode(0) #写一个listnode对象 值为0 next为 None
current=head1 # 写一个current 也指向head1 便于后续添加
pointer=head #用于指向head
while pointer is not None:
if pointer.val!=val: #如果值不相等
current.next=ListNode(pointer.val) #将它赋给当前current的next
current=current.next #将当前current移位到next
pointer=pointer.next#pointer移位到下一个
return head1.next#由于第一个值为0,循环也是从第二个开始,所以使用head1.next