题目
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
解答
三种方法:
- 双指针
- 递归
- 新开辟一个链表,增加空间复杂度
通过代码如下:
# 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