Skip to content

Latest commit

 

History

History
36 lines (29 loc) · 901 Bytes

0203. Remove Linked List Elements.md

File metadata and controls

36 lines (29 loc) · 901 Bytes

题目

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

我的思路

这道题要求删除链表中指定的值,只要遍历链表即可。首先,需要先创建一个空链表头,否则对原本的链表头无法删除。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeElements(self, head: ListNode, val: int) -> ListNode:
        res = ListNode(0)
        res.next = head
        l = res
        if not l:
            return
        while l.next:
            if l.next.val == val:
                l.next = l.next.next
            else:
                l = l.next
        return res.next