zoukankan      html  css  js  c++  java
  • [Leetcode 19] 19 Remove Nth Node From End Of List

    Problem:

    Given a linked list, remove the nth node from the end of list and return its head.

    For example,

       Given linked list: 1->2->3->4->5, and n = 2.
    
       After removing the second node from the end, the linked list becomes 1->2->3->5.
    

    Note:
    Given n will always be valid.
    Try to do this in one pass.

    Analysis:

    Use an auxilary pointer that n procedeed the current node. When the aux pointer is null, then the current pointer is the pointer to be removed;

    Also need a pointer that 1 succeed the current point for update.

    This is a one pass algorithm, so the time complecity is O(n); and space complexity is O(1);

    Code:

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     public ListNode removeNthFromEnd(ListNode head, int n) {
    14         // Start typing your Java solution below
    15         // DO NOT write main() function
    16         ListNode toRmv = head, aux = head, preRmv = head;
    17         
    18         for (int i=0; i<n; ++i)
    19             aux = aux.next;
    20         
    21         while (aux != null) {
    22             preRmv = toRmv;
    23             toRmv = toRmv.next;
    24             aux = aux.next;
    25         }
    26         
    27         if (toRmv == head) {
    28             head = head.next;
    29         } else {
    30              preRmv.next = toRmv.next;
    31         }
    32         
    33         return head;
    34     }
    35 }
    View Code

    Attention:

    If the Node to be removed is the head, need process it separately.

  • 相关阅读:
    微信公众号开发的时候code失效的问题
    微信公众平台测试号通过网页授权获取用户的信息
    做了一些mysql的习题 感觉用来应付面试是足够了
    springMVC在使用重定向跳转
    jsp获取标签数据
    再来一次atm机 用文本做的
    django mysql数据库配置
    django url控制器
    django初始要做的事情
    flask学习
  • 原文地址:https://www.cnblogs.com/freeneng/p/3086473.html
Copyright © 2011-2022 走看看