zoukankan      html  css  js  c++  java
  • LeetCode(203): Remove Linked List Elements

    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

    题意:给定一个链表,删除给定的元素。

    思路:对应本题可以使用双指针进行求解。求解的过程中要注意判断一些特殊的情况:链表为空和链表的前n个元素都为给定的元素等。

    代码:

    public ListNode removeElements(ListNode head, int val) {
            if(head==null) return null;
            while(head.val==val){
                if(head.next!=null)
                {
                 head = head.next;
                }else{
                    return null;
                }
            }
            if(head == null) return null;
            ListNode p=head,q=null;
            while(p!=null){
                if(p.val!=val){
                    q = p;
                }else{
                    q.next=p.next;
                }
                p=p.next;
            }
            return head;
        }
  • 相关阅读:
    EL表达式_1
    Servlet2
    Servlet1
    安装Tomcat
    Java日期时间3
    SpringCloud之Ribbon负载均衡
    SpringCloud之Eureka注册中心
    存储过程—增减字段
    880. Decoded String at Index
    977. Squares of a Sorted Array
  • 原文地址:https://www.cnblogs.com/Lewisr/p/5131425.html
Copyright © 2011-2022 走看看