这道题要求是在遍历一次的情况的,非常简单:
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int count = 0;
ListNode current = head;
ListNode preNode = head;
while(current.next != null){
current = current.next;
if(count++ >= n) preNode = preNode.next;
}
//特殊情况 首位的时候,首位前面没有ListNode
if(++count == n) head = head.next;
else preNode.next = preNode.next.next;
return head;
}
}