zoukankan      html  css  js  c++  java
  • 删除链表中倒数第n个节点

    1、给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。

    给出链表1->2->3->4->5->null和 n = 2.

    删除倒数第二个节点之后,这个链表将变成1->2->3->5->null.

    注意

    链表中的节点个数大于等于n

    挑战

    O(n)时间复杂度

    解题思路:刚开始看到倒数第n个节点,不禁感慨如果是数组就可以直接倒着来了。不过针对链表,一定要想起来最常用的方法---快慢指针。设一个fast和slow指针;快指针先走n步,然后快慢指针一起走,当fast==null,慢指针就值的是倒数第n个,然后删除就行。

     1 /**
     2  * Definition for ListNode.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int val) {
     7  *         this.val = val;
     8  *         this.next = null;
     9  *     }
    10  * }
    11  */ 
    12 public class Solution {
    13     /**
    14      * @param head: The first node of linked list.
    15      * @param n: An integer.
    16      * @return: The head of linked list.
    17      */
    18     ListNode removeNthFromEnd(ListNode head, int n) {
    19         // write your code here
    20         ListNode fast=head;
    21         ListNode result = new ListNode(0);
    22         result.next = head;
    23         for(int i=0;i<n-1;i++){
    24             fast = fast.next;
    25         }
    26         ListNode now = result;
    27         while(fast.next != null){
    28             fast = fast.next;
    29             now = now.next;
    30         }
    31         now.next = now.next.next;
    32         return result.next;
    33     }
    34 }
  • 相关阅读:
    博客园项目
    social-auth-app-django模块
    win10安装软件被阻止后
    expdp和impdp的用法
    EXPDP
    oracle常用的数据迁移方法
    使用spool导出数据
    无法创建spool文件
    sqlldr导入数据
    cmd 登录oracle
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/4993451.html
Copyright © 2011-2022 走看看