zoukankan      html  css  js  c++  java
  • 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.

     也可以用双指针(fast pointer) 来做,但是要注意 n = len的情况。

     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         // Note: The Solution object is instantiated only once and is reused by each test case.
    15         ListNode per = head;
    16         ListNode cur = head;
    17         ListNode before = head;
    18         int len = 0;
    19         while(per != null){
    20             per = per.next;
    21             len ++;
    22         }
    23         int num = len - n;
    24         if(num == 0)return head.next;
    25         else{
    26             per = head;
    27             for(int i = 0; i < num; i ++){
    28                 cur = per;
    29                 per = per.next;
    30             }
    31             cur.next = per.next;
    32             return head;
    33         }
    34     }
    35 }

     第二遍:

     1 public class Solution {
     2     public ListNode removeNthFromEnd(ListNode head, int n) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         ListNode header = new ListNode(-1);
     5         header.next = head;
     6         ListNode cur = header;
     7         ListNode per = header;
     8         ListNode fast = header;
     9         for(int i = 0; i < n; i ++){
    10             fast = fast.next;
    11         }
    12         while(fast != null){
    13             per = cur;
    14             fast = fast.next;
    15             cur = cur.next;
    16         }
    17         per.next = cur.next;
    18         return header.next;
    19     }
    20 }
  • 相关阅读:
    opencv环境的搭建,并打开一个本地PC摄像头。
    HDU ACM 4578 Transformation-&gt;段树-间隔的变化
    要毕业季
    netperf 而网络性能测量
    应用程序启动速度的优化
    Codeforces Round #264 (Div. 2) C Gargari and Bishops 【暴力】
    firefox os 2.0版模拟器QQ初体验
    DOMContentLoaded和window.onload
    HTML5管理与实际历史的分析(history物)
    Matlab Error (Matrix dimensions must agree)
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3371439.html
Copyright © 2011-2022 走看看