1. 删除链表的节点
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
方法一:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteNode(head, val):
if head.val == val:
return head.next
prev = head
next = prev.next
while next:
if next.val == val:
prev.next = next.next
prev = next
next = next.next
return head
方法二:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def deleteNode(head, val):
if not head:
return None
if head.val == val:
return head.next
head.next = deleteNode(head.next, val)
return head