给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例 1:
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
示例 2:
输入:head = [], val = 1
输出:[]
示例 3:
输入:head = [7,7,7,7], val = 7
输出:[]
提示:
列表中的节点数目在范围 [0, 104] 内
1 <= Node.val <= 50
0 <= val <= 50
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements
python
# 移除链表元素,所有值相同的元素全部删掉
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
class Solution:
# 删除头结点另做考虑
def removeElements1(self, head: ListNode, val: int) -> ListNode:
# rm值相同的头结点后,只要头部值相同,rm
while head != None and head.val == val: # 删除头部相同值,考虑一种情况,值全部相同时,head肯定指向None
head = head.next
if head == None: # 该情况适用于全部节点值和val同时,直接返回head
return head
prev = head # 头部的节点已处理,然后时一般情况下
# 确保当前节点还有节点
while prev.next != None:
if prev.next.val == val: # 如果遍历到某个节点下个节点的值同val时,前序节点指向后2节点
prev.next = prev.next.next
else: # 否则,继续遍历,直到相同或者遍历完
prev = prev.next
return head # 上面处理完后,相同值的节点都rm了,返回head
# 添加一个虚拟头结点
def removeElements2(self, head: ListNode, val: int) -> ListNode:
# 新建虚拟头结点
dummyNode = ListNode(-1) # 新建哨兵节点
dummyNode.next = head # 哨兵节点指向head
prev = dummyNode # 初始化前序节点
# 确保当前节点还有node
while prev.next != None: # 遍历前序节点
if prev.next.val == val: # 前序节点next节点值==val时,prev的节点指向下下个节点
prev.next = prev.next.next
else:
prev = prev.next # 否则,继续遍历
return dummyNode.next # 返回哨兵指向的next节点
# 递归方法
def removeElements3(self, head: ListNode, val: int) -> ListNode:
if head == None: # 空链表,返空
return None
head.next = self.removeElements3(head.next, val) # 否则,递归处理头结点的下个节点及后续节点
if head.val == val: # 如果头节点值==val,返回头结点的next
return head.next
else: # 否则,返回头结点(前面已经处理完所有同val的节点)
return head
golang
type ListNode struct {
Next *ListNode
Val int
}
// 虚拟头结点
func removeElements(head *ListNode, val int) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
cur := dummyHead
for cur != nil && cur.Next != nil {
if cur.Next.Val == val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return dummyHead.Next
}
// 处理头部节点
func removeElements2(head *ListNode, val int) *ListNode {
for head != nil && head.Val == val {
head = head.Next
}
if head == nil {
return nil
}
prev := head
for prev.Next != nil {
if prev.Next.Val == val {
prev.Next = prev.Next.Next
} else {
prev = prev.Next
}
}
return head
}
// 递归
func removeElements3(head *ListNode, val int) *ListNode {
if head == nil {
return nil
}
head.Next = removeElements3(head.Next, val)
if head.Val == val {
return head.Next
} else {
return head
}
}