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;
        }
    }
    
    有事评论区留言,也欢迎一起学习的伙伴
  • 相关阅读:
    文件操作
    MFC
    MFC
    MFC
    MFC
    大陆居民身份证验证方法(java)
    java validator的原理与使用
    解析搜狗词库(python)
    ICTCLAS改进的java版分词软件
    mvn打包
  • 原文地址:https://www.cnblogs.com/wt9866/p/13859646.html
Copyright © 2011-2022 走看看