记录刷题的过程。牛客和力扣中都有相关题目,此篇博客是力扣的题目描述。该系列默认采用python语言。
1、问题描述:
2、数据结构:
链表
3、题解:
# 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:
ptemp = head
res = ptemp
#找也许存在的结点
while ptemp and ptemp.val != val:
res = ptemp
ptemp = ptemp.next
#如果循环到None停止
if ptemp == None:
return None
#如果是头结点
if head.val == val:
return head.next
#如果是尾节点
if ptemp.next == None:
res.next = None
return head
#一般情况
res.next = ptemp.next
return head
4、复杂度分析:
时间复杂度:O(N)
空间复杂度:O(1)