Remove Linked List Elements
Remove all elements from a linked list of integers that have valueval.
Example Given:1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,val= 6 Return:1 --> 2 --> 3 --> 4 --> 5
题目大意:
从单链表中移除所有值为val的元素。
解题思路:
使用“哑节点”记录链表头部,防止删除第一个node,所以最后返回的也是dummy.next
循环遍历链表时使用pre, cur记录上一个元素和当前元素
注意:当找到相同元素时继续循环,因为有可能有多个相同元素
class Solution(object):
def removeElements(self, head, val):
"""
:type head: ListNode
:type val: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
pre, cur = dummy, head
while cur:
if cur.val == val:
pre.next = cur.next
else:
pre = cur
cur = cur.next
return dummy.next
Last updated
Was this helpful?