思路:
- 判空(如果链表为空,尝试访问或修改其内容将会引发错误。因此,在删除链表中的某个节点之前,你应该先检查链表是否为空。)
- 删除链表中的某一节点步骤:
- 定位节点:首先需要确定要删除的节点。通过遍历链表或直接访问到该节点来实现。
- 更新节点:一旦找到了要删除的节点,需要更新链表中该节点的位置。这通常涉及到修改该节点前一个节点的指针,让它直接指向该节点后一个节点。
- 释放内存:需要释放被删除节点的内存空间。若语言有自动垃圾回收机制(如Java或Python),那么不需要手动释放内存
初步构思:运行时间18ms
class Solution(object):
def deleteNode(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
#head为Null
if head == None:
return None
#头节点为val
if head.val == val:
head=head.next
return head
#其他节点为val
pre = head
while(pre.next != None):
if(pre.next.val==val):
pre.next = pre.next.next
return head
双指针方法:运行时间4ms
class Solution(object):
def deleteNode(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
cur = head
pre = None
while cur is not None:
#找到删除的元素
if cur.val== val:
#元素在头部
if cur == head:
head = cur.next
else:
#元素不在头部
pre.next = cur.next
return head
else:
pre = cur
cur = cur.next