zoukankan      html  css  js  c++  java
  • Leecode no.19 删除链表的倒数第 N 个结点

    package leecode;


    /**
    * 19. 删除链表的倒数第 N 个结点
    *
    * 给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
    *
    * 进阶:你能尝试使用一趟扫描实现吗?
    *
    *
    * @author Tang
    * @date 2021/9/22
    */
    public class RemoveNthFromEnd {

    /**
    * 双指针
    * index1用来找到正数第n个元素
    * 然后启动index0 index1同时向后遍历到头
    * 此时index0就是倒数第n个元素
    * (在head元素前再加一个首元素付给index0 用来删除操作)
    *
    * @param head
    * @param n
    * @return
    */
    public ListNode removeNthFromEnd(ListNode head, int n) {
    if(head == null) {
    return null;
    }
    ListNode first = new ListNode();
    first.next = head;

    ListNode index0 = first;
    ListNode index1 = head;

    int num = 1;
    while(index1.next != null) {
    if(num < n) {
    index1 = index1.next;
    num++;
    continue;
    }
    index0 = index0.next;
    index1 = index1.next;

    }
    index0.next = index0.next.next;
    return first.next;
    }


    public static void main(String[] args) {

    }


    }


    class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
  • 相关阅读:
    349. Intersection of Two Arrays
    346. Moving Average from Data Stream
    345. Reverse Vowels of a String
    344. Reverse String
    342. Power of Four
    POJ2823 Sliding Window
    《STL源码剖析》笔记
    [jobdu]扑克牌顺子
    [jobdu]第一个只出现一次的字符
    [jobdu]包含min函数的栈
  • 原文地址:https://www.cnblogs.com/ttaall/p/15319140.html
Copyright © 2011-2022 走看看