Leetcode - 19 Remove Nth Node From End of List (Medium)
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
解题思路:可能会删除第 0 个节点,所以要使用尾节点。
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummyHead = new ListNode(0);
dummyHead.next = head;
ListNode cur = dummyHead;
ListNode first = cur;
while(n-- >= 0){
first = first.next;
}
while(first != null){
first = first.next;
cur = cur.next;
}
cur.next = cur.next.next;
return dummyHead.next;
}