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 }
  • 相关阅读:
    .ds_store是什么文件
    style="background-image: url(__HOMEPAGE__/views/IMJ2V2/images/banner2.jpg)"
    前段实现图片懒加载
    thinkphp路由的作用
    thinkphp跨模块调用
    关于肥胖和美国为什么那么多胖子
    php中局部变量和全局变量
    thinkphp5项目--企业单车网站(七)
    thinkphp5项目--企业单车网站(六)
    XSS攻击及防御
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3371439.html
Copyright © 2011-2022 走看看