1、题目
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
2、解答
- 直接遍历法:链表遍历即可
- 递归法:这道题和翻转链表类似。
class Solution(object):
def removeElements(self, head, val):
"""
顺序遍历法
:type head: ListNode
:type val: int
:rtype: ListNode
"""
# 为什么要新建一个节点来指向head,是避免val对应的就是首节点
res = ListNode(val-1)
res.next = head
cur = head
prev = res
while cur is not None:
if cur.val!=val:
prev = cur
cur=cur.next
else:
next = cur.next
prev.next = next
cur = next
return res.next
def removeElements2(self, head, val):
"""
递归法
:type head: ListNode
:type val: int
:rtype: ListNode
"""
if head is None:
return None
head.next = self.removeElements2(head.next, val)
if head.val == val:
return head.next
else:
return head
这篇博客介绍了如何在Python中删除链表中所有值为特定整数的节点。提供了两种方法,一种是顺序遍历法,另一种是递归法。顺序遍历法通过新建一个虚拟头节点方便操作,逐个检查节点并移除不需要的节点;递归法则通过递归调用自身,处理链表的头部和剩余部分。这两种方法都能有效地实现链表的节点删除功能。
845

被折叠的 条评论
为什么被折叠?



