Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5
思路分析:这道题其实不难,就是遇到val的时候丢掉,让上一个结点的指针跳过当前结点。
# 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:
while head and head.val == val:
head = head.next
#先找到第一个不为val的结点,也可以用fake head解决
tmp,p1 = head, head and head.next
#将当前结点置为头结点,p1初始化为当前结点的下一个结点
#这里用了 head and head.next 意思是如果当前结点为空,那么 p1 就初始化为空
#如果 head 为真,表示头结点不为空,那么 and 返回的就是后边的 head.next
while p1:
if p1.val == val:
tmp.next = p1.next
else:
tmp = tmp.next
p1 = p1.next
return head