问题描述:
给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。返回删除后的链表的头节点。
示例 1:
输入: head = [4,5,1,9], val = 5
输出: [4,1,9]
解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
题目保证链表中节点的值互不相同
1、单指针
- 找到待删除节点的前一节点pre;
- 将 pre.next 设置为 pre.next.next
- 注意要考虑删除的是头节点的情况
# 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
while pre.next.val != None:
if pre.next.val == val:
pre.next = pre.next.next
break
pre = pre.next
return head
2、双指针
- 设置两个指针分别指向头节点,pre (要删除节点的前一节点)和 cur (当前节点);
- 遍历整个链表,查找节点值为 val 的节点,找到了就删除该节点,否则继续查找。
- 如果没找到,更新节点,继续遍历,pre.cur = cur.cur.next;如果找到的话,pre.next = cur.next
# 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, cur = head, head.next
while cur and cur.val != val:
pre, cur = cur, cur.next
if cur:
pre.next = cur.next
return head