203.移除链表元素

难度:简单
题目描述:
203.移除链表元素_第1张图片
思路总结:这题的点就是删除的是头结点的情况。解决方法也很简单,在头结点前面增加一个临时节点。
题解一:

# 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:
        #思路:删除元素一般都需要一个pre指针,有可能删除第一个元素时,通过增加一个头结点来返回
        hh = ListNode(0)
        hh.next = head
        pre = hh
        while head:
            if head.val == val:
                pre.next = head.next
            else:
                pre = head
            head = head.next
        return hh.next
        

题解一结果:
在这里插入图片描述

你可能感兴趣的:(朱滕威的面试之路)