zoukankan      html  css  js  c++  java
  • Leetcode: Remove Nth Node From End of List

    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.

     这道题要注意的Corner Case是:如果n比这个LinkedList的size大,那么就需要直接返回Head,如果相等,就把head删掉,返回head.next;基本做的方法呢,还是Runner Technique. 由于有可能head会被删掉,所以最好还是使用一个dummy node,dummy.next = head。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 class Solution {
    10     public ListNode removeNthFromEnd(ListNode head, int n) {
    11         ListNode dummy = new ListNode(-1);
    12         dummy.next = head;
    13         ListNode p1 = dummy, p2 = dummy;
    14         while (p2.next != null) {
    15             if (n > 0) {
    16                 n --;
    17             }
    18             else p1 = p1.next;
    19             p2 = p2.next;
    20         }
    21         if (n == 0) p1.next = p1.next.next;
    22         return dummy.next;
    23     }
    24 }
  • 相关阅读:
    unity3D相机缓慢看向目标物体
    设计原则
    unity3D中GUI标题内文字滚动效果
    python3.6中安装PyQt报错
    codeforces 515B.Drazil and His Happy Friends
    HDU 1029 Ignatius and the Princess IV
    POJ 1052 Plato's Blocks
    Uva220 Othello
    uva201 Squares
    uva1587 Box
  • 原文地址:https://www.cnblogs.com/EdwardLiu/p/3718033.html
Copyright © 2011-2022 走看看