删除链表的节点
题目:给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点
class ListNode:
def __init__(self, x, next=None):
self.val = x
self.next = next
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
if head.val == val:
return head.next
pre, cur = head, head.next
while cur and cur.val != val:
pre, cur = cur, cur.next
if cur:
pre.next = cur.next
return head
def print_list(head):
while head:
print(head.val,end=" ")
head = head.next
print()
ln=ListNode(0,ListNode(1,ListNode(2)))
print_list(ln)
sol=Solution()
a=sol.deleteNode(ln,1)
print_list(ln)