Skip to content

Commit

Permalink
剑指OfferII 021. 删除链表的倒数第n个结点
Browse files Browse the repository at this point in the history
  • Loading branch information
BGMer7 committed Jul 14, 2022
1 parent 883f5b8 commit 6c25a20
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/com/gatsby/offerII/_21RemoveNthFromEnd.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.gatsby.offerII;

import com.gatsby.ListNode;

/**
* @ClassName: _21RemoveNthFromEnd
* @Description: 剑指 Offer II 021. 删除链表的倒数第 n 个结点
* <p>
* 1 -> 2 -> 3 -> 4 -> 5
* @author: Gatsby
* @date: 2022/7/14 13:38
*/

public class _21RemoveNthFromEnd {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode fast = dummy;
ListNode slow = dummy;
while (n-- != 0) {
fast = fast.next;
}

while (fast != null && fast.next != null) {
fast = fast.next;
slow = slow.next;
}

slow.next = slow.next.next;
return dummy.next;
}
}


0 comments on commit 6c25a20

Please sign in to comment.