zoukankan      html  css  js  c++  java
  • 19. Remove Nth Node From End of List

    Given a linked list, remove the n-th node from the end of list and return its head.

    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.

    Follow up:

    Could you do this in one pass?

    two pointers,快指针先走n步,然后快慢指针一起走,当快指针走到最后一个node时,慢指针指向被删除节点的前一个

    注意:需要一个dummy node,因为head有可能被删除,初始时快慢指针都指向dummy node

    time: O(n), space: O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if(head == null) return head;
            ListNode dummy = new ListNode(0);
            ListNode p1 = dummy, p2 = dummy;
            p1.next = head;
            while(n > 0) {
                p1 = p1.next;
                n--;
            }
            while(p1.next != null) {
                p1 = p1.next;
                p2 = p2.next;
            }
            p2.next = p2.next.next;
            return dummy.next;
        }
    }
  • 相关阅读:
    Oozie — What Why and How
    git 用户手册
    整理笔记 C语言
    第一次理解通用链表
    C++ 通用队列类
    懂了这些,你才真正懂了C
    简单键盘驱动
    简述进程间通信方式
    几何原本
    GSP几何画板简介
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10135566.html
Copyright © 2011-2022 走看看