删除链表中的元素
删除链表中等于给定值 val 的所有节点。
样例
样例 1:
输入:head = 1->2->3->3->4->5->3->null, val = 3
输出:1->2->4->5->null
样例 2:
输入:head = 1->1->null, val = 1
输出:null
思路
遍历整个链表,当遇到元素和给定数值相等,则跳过该node,将上一个node的next属性修改为当下这个node的next属性。所以需要定义两个变量,pre:之前的node,cur:当前的node
1. 删除开头
由于cur是从第一位开始的,所以要添加一个condition,来比较第0位的数值和val的关系。如果相等,则删除开头的node。
head = head.next
如果所有元素都被删除,则直接返回
2. 删除中间
pre从第0位开始,cur从第一位开始
a. 如果当前值的val和给定val不相等,则向前移动
- pre向前移动一步
- cur向前移动一位
b. 如果当前值的val和val相等:
- 移动cur到下一位,保证pre位置不变
- 连接pre node和当前位置,即删除中间的node
3. 删除尾部
如果值和最后一位相等,例如5->3->null,pre指向5,cur指向3,按照第二步解法:
- pre:将5->3断开,并连接到cur.next, 则5->null
- cur:向前移动一位,从3移到null
所以第二步操作可以成功删除尾部,不会造成问题。
代码
class LinkedList:
def __init__(self, val):
self.val = val
self.next = None
def removeElements(head: LinkedList, val: int) -> ListNode:
# 删除开头
# if head is None, nothing to remove
while head is not None and head.val == val:
head = head.next
if head is None:
return head
#删除中间
pre, cur = head, head.next
while cur is not None:
if cur.val != val:
pre = pre.next
cur = cur.next
else:
cur = cur.next
pre.next = cur
return head