zoukankan      html  css  js  c++  java
  • 阿基用快慢指针带你刷遍leetcode的链表题——删除链表节点题

    剑指offer18.删除链表的节点

    class Solution {
        public ListNode deleteNode(ListNode head, int val) {
            if(head.val == val){
                return head.next;
            }
            ListNode fast = head.next;
            ListNode slow = head;
            while(fast.val != val && fast!=null){
                slow = fast;
                fast = fast.next;   
            }
            if(fast !=null){
                slow.next = fast.next;
            }
            return head;
        }
    }
    

    19.删除链表的倒数第N个节点

    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
           ListNode pre = new ListNode(0);
           pre.next = head;
           ListNode start = pre, end = pre;
           while(n != 0){
               start = start.next;
               n--;
           }
           while(start.next != null){
               start = start.next;
               end = end.next;
           }
           end.next = start;
           return pre.next;
        }
    }
    
    class Solution {
        public ListNode removeNthFromEnd(ListNode head,int n){
            ListNode pre = new ListNode(0) ;
            pre.next = head;
            ListNode fast = pre ,slow = pre;
            while(n>0){
                fast = fast.next;
                if(fast == null){
                    return null;
                }
                n--;
            }
            while(fast != null && fast.next != null){
                slow = slow.next;
                fast = fast.next;
            }
            slow.next = slow.next.next;
            return pre.next;
        }
    }
    
    有事评论区留言,也欢迎一起学习的伙伴
  • 相关阅读:
    MySQL记录
    yolo
    python 深度学习 库文件安装出错汇总
    OPENCV安装
    vs code安装leetcode插件
    打印机
    标注工具
    训练源代码训练数据集
    c++ 学习
    复现基于Pytorch的YOLOv3所踩的坑~
  • 原文地址:https://www.cnblogs.com/wt9866/p/13859646.html
Copyright © 2011-2022 走看看