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

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
     //题目要求一次遍历list即实现节点移除,使用双引用p与q来实现,q-p=n,向后遍历,当q无后继时到达list尾端,则p的next即为欲删除节点
    public class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            if (head == null) return head;
            if (head.next == null) return null;    //list只有一个node,潜台词就是n=1
            
            ListNode newhead = new ListNode(Integer.MIN_VALUE);    //被删除的节点可能是head,故设置一个newhead
            newhead.next = head;
            ListNode p = head;                //利用双引用实现一次遍历即删除倒数节点的目的
            ListNode q = head;                //示例list:1 2 3 4 5  5即为n=1时的情况
            
            for(int i=0;i<n;i++) q=q.next;    //运行了n次next,此时q为第n+1个节点,若n=2则p=1,q=3
            
            if(q == null){
            newhead.next = head.next;         //如果此时q即为null,则n必为list.length,即欲删除的为head
            return newhead.next;              //!!注意,此时必须return,否则继续向下执行q.next会出现空引用异常
            } 
            
            while(q.next != null){            //使p与q向后遍历,直至使q为list尾节点
                p = p.next;
                q = q.next;
            }
            ListNode removenode = p.next;     //此时,p.next即为欲删除的节点
            p.next = removenode.next;
            
            return newhead.next;
        }
    }
    
  • 相关阅读:
    App Inventor
    App Inventor趣味编程(网易课堂)
    学习App Inventor
    小学课程资源网
    mariadb数据类型
    docker监控容器
    docker网络
    项目——基于httpd镜像演示Dockerfile所有的指令
    Dockerfile介绍及指令详情
    docker——harbor
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444474.html
Copyright © 2011-2022 走看看