[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;
        
    }
}

 

你可能感兴趣的:(remove)