zoukankan      html  css  js  c++  java
  • 剑指 Offer 18. 删除链表的节点

    题目链接

    代码
    第一种写法,多使用了一个辅助指针

        public ListNode deleteNode(ListNode head, int val) {
            if (head == null) return null;
    
            // 首先分析在首部的情况
            if (head.val == val) {
                return head.next;
            }
    
            // 后面表示不在首部的情况,使用两个指针进行遍历,一个快,一个慢。
            ListNode temp = head;
            ListNode temp2 = head;
            temp = temp.next;
    
            while (temp != null && temp.val != val) {
                temp2 = temp2.next;
                temp = temp.next;
            }
    
            // 此时的必然结果是temp.val的值 == val,temp2在前一个
            temp2.next = temp.next;
    
            return head;
        }
    

    代码
    第二种写法,少使用一个辅助指针

        public ListNode deleteNode(ListNode head, int val) {
            if (head == null) return null;
    
            // 首先分析在首部的情况
            if (head.val == val) {
                return head.next;
            }
    
            // 后面表示不在首部的情况,使用两个指针进行遍历,一个快,一个慢。
            ListNode temp = head;
            while (temp.next != null && temp.next.val != val) {
                temp = temp.next;
            }
            temp.next = temp.next.next;
            // 此时的必然结果是temp.next.val的值 == val
            
            return head;
        }
    
  • 相关阅读:
    实体类实现序列化
    异常处理
    Springboot的模块化使用
    Springboot的开始
    RxJava用法
    okhttp的Post方式
    OKhttp使用
    soundPool声音池
    ScheduledExecutor定时器
    timer定时器
  • 原文地址:https://www.cnblogs.com/bears9/p/14009273.html
Copyright © 2011-2022 走看看