給定一個鏈表,刪除鏈表的倒數(shù)第 n 個節(jié)點,并且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數(shù)第二個節(jié)點后,鏈表變?yōu)?1->2->3->5.
說明:
給定的 n 保證是有效的。
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null) return head;
ListNode l = head; // 使用l表示要刪除的節(jié)點
ListNode r = head;
ListNode pre = head; //使用pre來記錄要刪除節(jié)點的上一個節(jié)點
for (int i = 0; i < n ; i++) {
r = r.next;
}
while (r != null) {
r = r.next;
pre = l;
l = l.next;
}
if (l == head) return head.next; //邊界判斷,如果要刪除的是頭節(jié)點,直接返回head.next
pre.next = l.next; //刪除l節(jié)點
return head;
}