25.Remove Nth Node From End of List(删除链表的倒数第n个节点)

Level:

  Medium

题目描述:

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.

思路分析:

  题目要求删除链表的倒数第n个节点,首先我们需要判断n是否在有效范围,然后我们计算出链表的长度,求倒数第n个,就是求正数第len-n个。

代码:

public class ListNode{
    int val;
    ListNode next;
    public ListNode(int x ){
        val=x;
    }
}
public class Solution{
    public ListNode removeNthFromEnd(ListNode head,int n){
        if(head==null)
            return null;
        int len=0;
        ListNode pNode=head;
        while(pNode!=null){
            len++;
            pNode=pNode.next;
        }
        if(n>len)
            return null;
        if(len==1&&len==n)
            return null;
        if(len==n)
            return head.next;
        ListNode pNode2=head;
        for(int i=0;i<len-n-1;i++){
            pNode2=pNode2.next;
        }
        pNode2.next=pNode2.next.next;
        return head;
    }
}