好吧,參考的答案…感覺這種思路棒棒的…and以後要用java…
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head==null) return null;
//定義兩個指針,第一個保持指向最初的head指針
//使head指針移動,先到達訪問第n個結點,第二個指針開始出發
//則當head訪問完末尾結點時,第二個正好到達從後往前數的第n個結點
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode follower = dummy;
for(int i=0;i<n;i++){
if(head==null) return null;
head = head.next;
}
while(head!=null){
head = head.next;
follower = follower.next;
}
follower.next = follower.next.next;
return dummy.next;
}
}