给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
示例一:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例二:
输入: head = [4,5,1,9], val = 1
输出: [4,5,9]
解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
class ListNode():
def __init__(self):
self.val = 0
self.next = None
class Solution():
def deleteNode(self, head: ListNode, val: int) -> ListNode:
if head.val == val: return head.next
temp = head
while temp.next is not None:
if temp.next.val is not None:
temp.next = temp.next.next
break
temp = temp.next
return head
node3 = ListNode()
node3.val = 3
node3.next = None
node2 = ListNode()
node2.val = 2
node2.next = node3
node1 = ListNode()
node1.val = 1
node1.next = node2
s = Solution()
head = s.deleteNode(node1, 2)
print(head)