/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param n int整型
* @return ListNode类
*/
public ListNode removeNthFromEnd (ListNode head, int n) {
// write code here
if (head == null || n < 1) {
return head;
}
int len = 0;
ListNode cur = head;
while (cur != null) {
len++;
cur = cur.next;
}
if (len < n) {
return head;
} else if (len == n) {
return head.next;
}
ListNode pre = head;
cur = pre;
int i = 0;
ListNode next = null;
while (i < len - n) {
next = cur.next;
pre = cur;
cur = next;
i++;
}
pre.next = cur.next;
cur.next = null;
return head;
}
}