题目来源:力扣
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
输入:head = [1,2,6,3,4,5,6], val = 6 输出:[1,2,3,4,5]
输入:head = [], val = 1 输出:[]
输入:head = [7,7,7,7], val = 7 输出:[]2. 题解
首先,去掉LinkedNode直接的连接(即next关系),重新初始化。再将非val的节点存储到list中,重新生成链表。和reverse链表的思路一致。代码如下,
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
Link_lst = []
current = head
# 首先排除特殊情况
if current is None:
return current
# 直接return也可
# 将非val的ListNode存储起来
while not current.next is None:
if current.val != val:
Link_lst.append(ListNode(current.val))
current = current.next
if current.val != val:
Link_lst.append(current)
# 重新生成LinkedList
if len(Link_lst)==0:
return
else:
r = Link_lst[0]
current = r
for i in Link_lst[1:]:
current.next = i
current = i
return r



