LeetCode- 移除链表元素
题目描述
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
示例一:
示例二:
示例三:
思路说明
定义一个空的链表,如果原链表上节点的值不等于val,则拼接上这个节点,否则,判断下一个节点。
返回的时候返回定义链表的next,则为新链表的新的头节点。
详见代码。欢迎大家批评指正。
代码实现
# 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
"""
if head is None:
return head
else:
p=ListNode()
q=p
while head:
if head.val == val:
head=head.next
else:
q.next=head
q=head
head=head.next
q.next=None
return p.next
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-linked-list-elements/