今天这题一次就通过了,归功于我将思路简单画在了纸上,分别考虑了一般情况和边界情况。循环边界也能够一目了然,不然循环边界真的把人搞得头大,很容易出错。
整体思路如下:
最终代码如下:
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode slow = dummyNode;
ListNode fast = dummyNode;
for (int i = 1; i <= n+1; i++){
fast = fast.next;
}
while (fast != null){
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return dummyNode.next;
}