• LeetCode 19. Remove Nth Node From End of List


    原题链接在这里:https://leetcode.com/problems/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.

    题解:

    Method 1:算出总长度, 再减去n, 即为要从头多动的点。但要新要求, only one pass.

    Method 2:两个指针,一个runner, 一个walker, runner先走n步,随后runner和walker一起走,直到runner指为空。

    Note:1. 都是找到要去掉点的前一个点记为mark, 再通过mark.next = mark.next.next去掉对应应去掉的点.

    2. 注意去掉list头点的情况,所以要建立一个dummy head. e.g. 1->2, n = 2.

    Time Complexity: O(n), n是list长度. Space: O(1).

    AC Java: 

     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 public class Solution {
    10     public ListNode removeNthFromEnd(ListNode head, int n) {
    11         /*Method 1
    12         if(head == null)
    13             return head;
    14         int len = 0;
    15         ListNode temp = head;
    16         while(temp != null){
    17             temp = temp.next;
    18             len++;
    19         }
    20         if(len < n){
    21             return head;
    22         }
    23         int moveNum = len - n;
    24         ListNode dunmy = new ListNode(0);
    25         dunmy.next = head;
    26         temp = dunmy;
    27         while(moveNum > 0){
    28             temp = temp.next;
    29             moveNum--;
    30         }
    31         temp.next = temp.next.next;
    32         return dunmy.next;
    33         */
    34         
    35         //Method 2
    36         if(head == null || n == 0)
    37             return head;
    38 
    39         ListNode dummy = new ListNode(0);
    40         dummy.next = head;
    41         ListNode walker = dummy;
    42         ListNode runner = dummy;
    43         
    44         while(n>0 && runner.next != null){
    45             runner = runner.next;
    46             n--;
    47         }
    48         
    49         while(runner.next != null){
    50             walker = walker.next;
    51             runner = runner.next;
    52         }
    53         
    54         walker.next = walker.next.next;
    55         return dummy.next;
    56     }
    57 }
  • 相关阅读:
    机器学习的数学基础
    Numpy + matplotlib + pandas 用法示例
    笔记:《ZeroMQ》
    Bash 常用快捷键
    Python网络爬虫
    Bash-Script 应用案例
    Bash-Script 语法详解
    ADB的使用
    ROS概述
    架构风格
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4825012.html
Copyright © 2020-2023  润新知