(java)Remove Linked List Elements

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

思路:判断p.next.val是否等于val,如果等于则p.next=p.next.next;

注意边界,考虑到最后一个点,while循环的条件应该是p!=null && p.next!=null;

代码如下(已通过leetcode)

public class Solution {
   public ListNode removeElements(ListNode head, int val) {
    while(head!=null && head.val==val) head=head.next;
    ListNode p=head;
    if(p==null) return null;
       while(p!=null&&p.next!=null) {
       
        if(p.next.val==val) {
        if(p.next.next==null) p.next=null;
        else p.next=p.next.next;
       
        else p=p.next;
       }
       return head;
   }
   
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
LinkedBlockingQueue is a class in Java that implements the BlockingQueue interface. It is an implementation of a queue with a linked list data structure. The LinkedBlockingQueue class is used to implement producer-consumer design patterns where producers add elements to the queue, and consumers remove elements from the queue. The LinkedBlockingQueue has the following characteristics: - It is thread-safe and can be used in a multi-threaded environment. - It has an optional capacity limit that can be specified during initialization. - If the capacity limit is not specified, the queue can grow indefinitely. - If the queue is full, any attempt to add an element to the queue will block until space becomes available. - If the queue is empty, any attempt to remove an element from the queue will block until an element becomes available. Some of the methods available in the LinkedBlockingQueue class include: - add(E e): Adds an element to the queue, throwing an exception if the queue is full. - offer(E e): Adds an element to the queue, returning false if the queue is full. - put(E e): Adds an element to the queue, blocking until space becomes available. - take(): Removes and returns an element from the queue, blocking until an element becomes available. - poll(long timeout, TimeUnit unit): Removes and returns an element from the queue, waiting up to the specified time if necessary for an element to become available. Overall, LinkedBlockingQueue is a very useful class in Java for implementing thread-safe queues in multi-threaded environments.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值