19Remove Nth Node From End of List

来源:互联网 发布:淘宝代做毕业设计真假 编辑:程序博客网 时间:2024/05/01 15:36
/**
 * 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) {
if(head==null) return null;
       ListNode res = head;
       int len = 0;
       while(res!=null){
        res = res.next;
        ++len;
       }
       if(len < n) return null;
       if(len==n) return head.next;
       res = head;
       for(int i=0;i<len-n-1;++i){
        res = res.next;
       }
       res.next = res.next.next;
       return head;
}
}
0 0