Remove all elements from a linked list of integers that have value val.
Example
Given: 1 –> 2 –> 6 –> 3 –> 4 –> 5 –> 6, val = 6
Return: 1 –> 2 –> 3 –> 4 –> 5
java code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode removeElements(ListNode head, int val) {
while(head != null && head.val == val) {
head = head.next;
}
if(head == null) return null;
ListNode target = head;
while(target != null && target.next != null) {
if(target.next.val == val) {
target.next = target.next.next;
}
if(target.next != null && target.next.val != val) {
target = target.next;
}
}
return head;
}
}
386ms =,=
ruby code实现如下:
# Definition for singly-linked list.
# class ListNode
# attr_accessor :val, :next
# def initialize(val)
# @val = val
# @next = nil
# end
# end
# @param {ListNode} head
# @param {Integer} val
# @return {ListNode}
def remove_elements(head, val)
while(head != nil && head.val == val)
head = head.next
end
return nil if head == nil
target = head
while(target != nil && target.next != nil)
if(target.next.val == val)
target.next = target.next.next
end
if(target.next != nil && target.next.val != val)
target = target.next
end
end
return head
end
146ms 在这里解释执行还是快点。。。