題目:給定單向鏈表的頭指針和一個要刪除的節點的值,定義一個函數刪除該節點。返回刪除後的鏈表的頭節點。注意:此題對比原題有改動
示例 1:
輸入: head = [4,5,1,9], val = 5 輸出: [4,1,9]
解釋: 給定你鏈表中值為 5的第二個節點,那麼在調用了你的函數之後,該鏈表應變為 4 -> 1 -> 9.
示例 2:輸入: head = [4,5,1,9], val = 1 輸出: [4,5,9]
解釋: 給定你鏈表中值為 1的第三個節點,那麼在調用了你的函數之後,該鏈表應變為 4 -> 5 -> 9.
程序說明:
全部代碼:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteNode(self, head: ListNode, val: int) -> ListNode:
if head.val == val:
return head.next
pre = head
cur = pre.next
while cur:
if cur.val == val:
pre.next = cur.next
return head
pre = cur
cur = cur.next
return head
題目來源:力扣(LeetCode)