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


    /**
     * 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) {
            //题眼:两个指针,一快一慢,步长为n
            //注意几点:
            //1.判断输入的整数范围
            //2.删除的是头结点的处理方式(画图)
            
            if(n<=0)return null;
            ListNode right=head;
            while(n>0){
                right=right.next;
                n--;
            }
            ListNode left=head;
            if(right==null)return head.next;//注意删除第一个节点的例外
            while(right.next!=null){
                left=left.next;
                right=right.next;
            }
            left.next=left.next.next;//删除节点
             return head;
            
        }
    }
  • 相关阅读:
    第四次上机练习
    第五周上机练习
    第四周作业
    第二次上机练习
    第三周作业
    第一次上机练习
    第一次作业
    第五周上级作业
    第一次上机0.0
    java第六周作业
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4627193.html
Copyright © 2011-2022 走看看