删除链表中等于给定值 val 的全部节点。指针
示例:code
输入: 1->2->6->3->4->5->6, val = 6 输出: 1->2->3->4->5
三种方法:递归
经过代码以下:rem
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # # 方法一:双指针。 时间复杂度O(n),空间复杂度O(1) def removeElements(self, head: ListNode, val: int) -> ListNode: thead = ListNode(-100) thead.next = head p, c = thead, head while c: if c.val == val: p.next = c.next c = c.next else: p = c c = c.next return thead.next # # 方法三: # # 最笨方法,新建一条链表存。时间复杂度O(n),空间复杂度O(n) # def removeElements(self, head: ListNode, val: int) -> ListNode: # thead = ListNode(-100) # p = thead # while head: # if head.val != val: # temp = ListNode(head.val) # p.next = temp # p = temp # head = head.next # return thead.next # # 方法二:递归 # # 回溯时,判断当前节点的值是否是val。 时间复杂度O(n),空间复杂度O(n) # def removeElements(self, head: ListNode, val: int) -> ListNode: # if not head: # return head # head.next = self.removeElements(head.next, val) # if head.val == val: # return head.next # return head