https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
返回删除后的链表的头节点。
思路:双指针,一个指针指向当前节点,一个指针指向当前节点的前一个节点(pre),当判断当前节点为要删除节点时,将pre的next节点更改为当前节点的next节点即可。
时间复杂度1,空间复杂度n
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head is None:
return head
if head.val == val:
return head.next
pre = head
tmp = head.next
while tmp != None:
if tmp.val == val:
pre.next = tmp.next
break
pre = tmp
tmp = tmp.next
return head