首页 > 其他 > 详细

阿基用快慢指针带你刷遍leetcode的链表题——删除链表节点题

时间:2020-10-22 19:35:17      阅读:37      评论:0      收藏:0      [点我收藏+]

剑指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;
    }
}

阿基用快慢指针带你刷遍leetcode的链表题——删除链表节点题

原文:https://www.cnblogs.com/wt9866/p/13859646.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!