zoukankan      html  css  js  c++  java
  • 力扣203题(移除链表元素)

     203、移除链表元素

     具体实现:

    如果头结点是要删除的元素选择两种方式

    1、直接使用原来的链表进行删除操作

    2、设置一个虚拟头结点再进行删除操作

    代码:

     1、不设置虚拟结点

    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            while (head != null && head.val == val){//如果头结点是要删除的值,就让头结点指向下一个节点
                head = head.next;
            }
            if (head == null){
                return head;
            }
             ListNode pre = head;
             ListNode cur = head.next;
             while (cur != null) {
                if (cur.val == val){
                    pre.next = cur.next;
                }
                else{
                    pre = cur;
                }
                cur = cur.next;
            }
            return head;
        }
    }

    2、设置虚拟头结点

    class Solution {
        public ListNode removeElements(ListNode head, int val) {
            if (head == null){
                return head;
            }
            ListNode dummy = new ListNode(-1, head);
            ListNode pre = dummy;
            ListNode cur = head;
            while (cur != null) {
                if (cur.val == val){
                    pre.next = cur.next;
                }
                else{
                    pre = cur;
                }
                cur = cur.next;
            }
            return dummy.next;
        }
    }
  • 相关阅读:
    FPGA开发全攻略——FPGA选型
    FPGA开发全攻略——FPGA开发基本流程
    希尔伯特变换的物理意义
    无线通信方式
    FPGA DDR3调试
    FPGA调试光纤模块
    FPGA FIFO深度计算
    Xilinx FPGA LVDS应用
    电源设计注意事项
    波特图与零极点
  • 原文地址:https://www.cnblogs.com/zhaojiayu/p/15389854.html
Copyright © 2011-2022 走看看