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

    解法:

      题目要求移除倒数第n个节点,并且说明了n一定是有效的,限定一次遍历解决问题。首先定义两个指针 first 和 last,first 指向第一个节点,last 指向第 n+1 个节点;两个节点同时向后撸,直到 last.next 为 null 的时候,说明当前 first.next 即为待删除节点,直接 first.next.next = first.next 即可删除,然后返回 head。注意,如果一开始的时候 last 就为 null,说明 head 节点就是带删除的节点,直接返回 head.next 即可。

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            ListNode first = head;
            ListNode last = head;
            while (n-- > 0) {
                last = last.next;
            }
            
            if (last == null) {
                return head.next;
            }
            
            while (last.next != null) {
                first = first.next;
                last = last.next;
            }
            
            first.next = first.next.next;
            return head;
        }
    }
  • 相关阅读:
    题解 CF702F 【T-Shirts】
    题解 CF914G 【Sum the Fibonacci】
    CF258D 【Little Elephant and Broken Sorting】
    socket 私有服务端验证方法
    Gateway + Oauth2 + Security认证与授权 [更新中]
    串并转换和并串转换
    序列检测机【转】
    浮点数的定点化
    Verilog实现同步FIFO和异步FIFO
    频率检测计
  • 原文地址:https://www.cnblogs.com/strugglion/p/6413585.html
Copyright © 2011-2022 走看看