链表问题。这种问题主要是指针的操作,需要细心一点,另外这个问题的附加条件是只遍历一次。参考了讨论里面的解答才做出来的。首先用一个先驱指针先前进n步,然后先驱和后继同时前进,等先驱遇到null的时候,后继指针就到了该删除节点的地方了。如果先驱指针前进n步后已经到达null,那直接把head往后指一个节点就行了。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode temp = head;
ListNode pioneer = head;
while (pioneer != null) {
if (--n >= 0) {
pioneer = pioneer.next;
if (pioneer == null) {
head = head.next;
}
} else {
if (pioneer.next == null) {
temp.next = temp.next.next;
break;
} else {
temp = temp.next;
pioneer = pioneer.next;
}
}
}
return head;
}
}